How to make Rust trait like feature in dlang ?

Mike Franklin slavo5150 at yahoo.com
Mon Jun 17 11:26:21 UTC 2019


On Monday, 17 June 2019 at 04:25:26 UTC, Newbie2019 wrote:

> D can do it, but much less elegant. compare to Rust, d is like 
> granny language.

Actually, D doesn't require all of the boilerplate to set up the 
interface and the implementation checking.  You just type it up 
because the compiler will tell you when something's not right.

```
import std.stdio;

struct TcpSocket
{
     int send(ubyte[] data, int len) { writeln("TcpSocket send"); 
return len; }
     int recv(ubyte[] buff, int len) { writeln("TcpSocket recv"); 
return len; }
}

struct UdpSocket
{
     int send(ubyte[] data, int len) { writeln("UdpSocket send"); 
return len; }
     int recv(ubyte[] buff, int len) { writeln("UdpSocket recv"); 
return len; }
}

struct UnixSocket
{
     int send(ubyte[] data, int len) { writeln("UdpSocket send"); 
return len; }
     int recv(ubyte[] buff, int len) { writeln("UdpSocket recv"); 
return len; }
}

struct NotASocket { }

void Use(T)(T socket)
{
     socket.send([], 0);
     socket.recv([], 0);
}

void main()
{
     TcpSocket socket;
     socket.Use();   // Works out of the box without any interface 
boilerplate

     NotASocket noSocket;
     noSocket.Use(); // Error: no property `send`/`recv` for type 
`NotASocket`
}
```
https://run.dlang.io/is/FpfkS6

I didn't even have to create an interface or implement one, yet 
the compiler knew what to do.

If you really wanted to do the interface boilerplate like Rust, 
that's also possible in D, but unnecessary IMO.  You could also 
use classes w/ interfaces, something Rust doesn't even have.

So in this situation, D gives you everything Rust has and more 
with less boilerplate.

Mike


More information about the Digitalmars-d mailing list