On Sunday, 21 May 2017 at 08:44:31 UTC, David Zhang wrote:
Hi,
I was reading a bit about this in Rust, and their enum type. I
was wondering if this is replicate-able in D. What I've got
right now is rather clunky, and involves using
`typeof(return).ok` and `typeof(return).error)`.
While that's not too bad, it does involve a lot more typing,
and thus more area for human error.
If you're not familiar with the Result and Option types, it
allows you to do something like this:
---
Result!(string, ErrorEnum) someFunction(...)
{
return Ok("Hello!");
}
Result!(string, ErrorEnum) someFunction2(...)
{
return Error(ErrorEnum.dummyError);
}
---
I'm not entirely sure it's possible... but I figured I might
give it a try.
have free functions
Result!(T, ErrorEnum) ok(T)(T t) { return Result(t); }
Result!(T, ErrorEnum) error(T)(ErrorEnum e) { return Result(e); }
then go
if (!foo)
return ok(42);
else
return error(Error.fooHappened);