How to make Rust trait like feature in dlang ?
Newbie2019
newbie2019 at gmail.com
Mon Jun 17 04:25:26 UTC 2019
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.
More information about the Digitalmars-d
mailing list