O'Reilly logo

D Cookbook by Adam D. Ruppe

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Duck typing to a statically-defined interface

A distinguishing feature of the Go programming language is static interfaces that do not need to be explicitly inherited. Using D's compile-time reflection and code generation capabilities, we can do something similar.

Getting ready

Let's start by defining a goal. We'll write an interface and a struct block that could implement the interface, but which does not explicitly inherit from it (the struct blocks in D can not inherit from the interfaces at all). We'll also write the following brief function that uses the interface to perform a task:

interface Animal { void speak(); void speak(string); } struct Duck { void speak() { import std.stdio; writeln("Quack!"); } void speak(string whatToSay) { import ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required