How to make Rust trait like feature in dlang ?
XavierAP
n3minis-git at yahoo.es
Mon Jun 17 14:39:06 UTC 2019
On Monday, 17 June 2019 at 10:25:57 UTC, lili wrote:
>
> Can't get your point. think what? C++ not support conception
> now.
> D not yet. But conception is really powerful. So is dlang will
> support it.
> for example: struct allow inherited interface, implement
> conception.
I think you mean C++ "concepts"[1]?. These do exist in D (since
much earlier); they are called template constraints[2]:
struct TcpSocket { /*...*/ }
struct UdpSocket { /*...*/ }
// Template constraint:
template isSocket(T)
{
import std.traits;
enum bool isSocket = /*...*/
}
auto UseSocket(ISocket)(ISocket sk)
if(isSocket!ISocket)
{ /*...*/ }
Still, template constraints or concepts work differently from
Rust traits (or C# interfaces, which can be implemented by
structs as well as classes). But they can be not so different
ways to accomplish the same.
One difference is that D requires this "polymorphism" to be
templated, while C# and Rust allow structs to implement
interfaces/traits. (Probably there is no reason why D could or
should not add this capability, at least as long as it does not
turn structs from values to references when assigned to an
interface value.)
This templated approach on the other hand is more flexible.
Inheritance is not a sin as many people say nowadays, but it
introduces rigidity in your design, and is not extensible for
library users.
_______
[1] https://en.wikipedia.org/wiki/Concepts_(C%2B%2B)
[2] https://dlang.org/spec/template.html#template_constraints
More information about the Digitalmars-d
mailing list