How to make Rust trait like feature in dlang ?

bauss jj_1337 at live.dk
Mon Jun 17 07:41:22 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.

Maybe that's because they are not supposed to be implemented like 
that in D.

Surprise, surprise.

> compare to Rust, d is like granny language.

Based on what merit?


More information about the Digitalmars-d mailing list