How to make Rust trait like feature in dlang ?

lili akozhao at tencent.com
Mon Jun 17 12:11:19 UTC 2019


On Monday, 17 June 2019 at 11:26:21 UTC, Mike Franklin wrote:
> 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

Yes, It's ok. but this did not represent to an conception under 
code.
I want to explicitly represent this is a SocketLike cenception.
because i want conception oriented programming not type oriented, 
this is more powerful in GP.
now I find a way that is use mixin template.
```
mixin template SocketLike {
    int send(ubyte[] data, int len);
    int recv(ubyte[] buff, int len);
}

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

struct UdpSocket {
    mixin SocketLike;
    //implement SocketLike behavior
    int send(ubyte[] data, int len) { writeln("TcpSocket send"); 
return len; }
    int recv(ubyte[] buff, int len) { writeln("TcpSocket recv"); 
return len; }
}
```
this not perfect not this is already abstract an SocketLike 
conception.


More information about the Digitalmars-d mailing list