structs inheriting from and implementing interfaces

Nicholas Wilson iamthewilsonator at hotmail.com
Fri Dec 29 12:39:25 UTC 2017


On Friday, 29 December 2017 at 12:03:59 UTC, Mike Franklin wrote:
> In C#, structs can inherit from and implement interfaces.
>
> ----
> using System;
>
> interface IPrint
> {
>     void Print();
> }
>
> struct MyStruct : IPrint
> {
>     public void Print()
>     {
>         Console.WriteLine(ToString());
>     }
> }
>
> public class Program
> {
>     public static void Main()
>     {
>         MyStruct s = new MyStruct();
>         s.Print();
>     }
> }
> ----
> https://dotnetfiddle.net/lpXR1O
>
> But in D it doesn't appear possible.
> ----
> import std.stdio;
>
> interface IPrint
> {
>     void print();
> }
>
> // Error: base classes are not allowed for struct, did you mean 
> ;?
> struct MyStruct : IPrint   // Error: base classes are not 
> allowed for struct, did you mean ;?
> {
>     void print()
>     {
>         writeln("MyStruct");
>     }
> }
>
> void main()
> {
> 	MyStruct s;
>     s.Print();
> }
> ----
> https://run.dlang.io/is/j4xwla
>
> Is that simply because it hasn't been implemented or suggested 
> yet for D, or was there a deliberate design decision?
>
> Thanks for your insight,
>
> Mike

The problem is that interfaces are a runtime thing (e.g. you can 
cast a class to an interface)
structs implement compile time interfaces via template duck 
typing (usually enforced via an if()).
you could probably write a wrapper that introspected an interface 
and enforced that all members were implemented.


More information about the Digitalmars-d-learn mailing list