Little demo of allowing basic types to implement interfaces.
Rory McGuire
rjmcguire at gmail.com
Tue Sep 3 23:26:05 PDT 2013
On Wednesday, 4 September 2013 at 00:56:55 UTC, Rory McGuire
wrote:
> I was wondering if its possible to do interfaces the way
> #golang does it
> but in #dlang.
>
> Here is my first try: https://gist.github.com/rjmcguire/6431542.
> Any help on making this smaller would be awesome.
>
> Cheers,
> R
Here is another example use, checking if a type can convert
itself to ubyte[]:
void main() {
int i = 0x34342343;
writebytes(i);
}
interface IRawBytes { ubyte[] bytes(); }
void writebytes(T)(T item) if (Implements!(T, IRawBytes)) {
import std.stdio : writeln;
writeln(item.bytes);
}
ubyte[] bytes(ref int i) {
ubyte* ptr;
ptr = cast(ubyte*)&i;
return ptr[0..i.sizeof];
}
In the above example you get a nice error message if int does not
have the "bytes" ufcs function.
missing: ubyte[] int.bytes()
int, does not implement interface: traits.IRawBytes
traits.d(18): Error: template traits.writebytes does not match
any function template declaration. Candidates are:
...
More information about the Digitalmars-d-announce
mailing list