Book Image

D Cookbook

By : Adam Ruppe
Book Image

D Cookbook

By: Adam Ruppe

Overview of this book

Table of Contents (21 chapters)
D Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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 std.stdio;
    writeln("Quack! ", whatToSay);
  }
}

void callSpeak(Animal a) {
  a.speak();
  a.speak("hello");
}

void main() {
  Duck d;
  // callSpeak(wrap!Animal(&d)); // we want to make this line work
}

The callSpeak...