structs inheriting from and implementing interfaces

Seb seb at wilzba.ch
Fri Dec 29 12:11:30 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

I think it simply hasn't been implemented, but I am not sure here 
because you could simply insert a `static assert` in there (and 
probably have something like `hasInterface!(Interface, 
YourStruct)`. Similarly multiple `alias this` is a request that 
often comes up.


More information about the Digitalmars-d-learn mailing list