How to make Rust trait like feature in dlang ?

Alex sascha.orlov at gmail.com
Sun Jun 16 19:13:05 UTC 2019


On Sunday, 16 June 2019 at 15:56:41 UTC, lili wrote:
> Hi, guys:
>    I really like Rust trait feature. Use it can implement 
> duck-type simple.
>    base on inherited OO is complex and hard, because you need 
> to design inherited tree well.
>    and this is not easy. In real word need runtime polymorphic 
> is uncommon. lots of is just need compile time polymorphic.
>
> for example: design a network socket lib you need to implement 
> TCP,UDP,Unix socket and these
> sockets have need implement send, recv function.
>
> interface SocketLike {
>    int send(ubyte[] data, uint32 len);
>    int recv(ubyte[] buff, uint32 len);
> }
>
> struct TcpSocket : SocketLike {...} // in dlang struct can not 
> allows to inherited interface
> struct UdpSocket : SocketLike {...}
> struct UnixSocket : SocketLike {...}
>
> function UseSocketLike(SocketLike socket)
> {
>    socket.recv()
>     ....
> }
>
>
> I not need runtime polymorphic, just need compiler check real 
> argument is SocketLike type.
> How do this, can dlang support conception like feature.

Beyond the fact, that such questions should be placed in the 
learn forum section, you can achieve such checks via templating 
the function and usage of template constraints.

https://dlang.org/spec/template.html#template_constraints

For example,
´´´
import std;

enum bool isSocketLike(T) =
     is(ReturnType!((T r) => r.send((ubyte[]).init, uint.init)) == 
int)
     && is(ReturnType!((T r) => r.recv((ubyte[]).init, uint.init)) 
== int);

void main()
{
     static assert(isSocketLike!T);
     static assert(!isSocketLike!F);
     UseSocketLike(T.init);
     static assert(!__traits(compiles, UseSocketLike(F.init)));
}

struct T
{
     int send(ubyte[] data, uint l){return 0;}
     int recv(ubyte[] buff, uint l){return 0;}
}

struct F{}

auto UseSocketLike(T)(T socket) if(isSocketLike!T)
{
     // ... and so on ...
}
´´´


More information about the Digitalmars-d mailing list