How to make Rust trait like feature in dlang ?

Jacob Carlborg doob at me.com
Sun Jun 16 19:34:03 UTC 2019


On 2019-06-16 17:56, 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.

Have a look at how Mecca implements socket addresses [1].

[1] 
https://github.com/weka-io/mecca/blob/b36254e205ff8520effaa9ccc8bf74d73a28c639/src/mecca/lib/net.d#L538-L545


-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list