How to make Rust trait like feature in dlang ?

Alex sascha.orlov at gmail.com
Mon Jun 17 08:51:30 UTC 2019


On Monday, 17 June 2019 at 04:25:26 UTC, Newbie2019 wrote:
> On Sunday, 16 June 2019 at 19:13:05 UTC, Alex wrote:
>>
>> 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 ...
>> }
>> ´´´
>
> D can do it, but much less elegant. compare to Rust, d is like 
> granny language.

I don't get your point.

If you want a socket implementation, use (or use as an 
inspiration) an existent library, as Jacob mentioned.

If you want some static checks of your code while developing, you 
could let away  half of the code I showed. The compiler will 
check all interface usages anyway.


More information about the Digitalmars-d mailing list