Implicit conversion from 'Ok' to 'Result' type when returning functions

David Zhang via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon May 22 19:09:24 PDT 2017


On Sunday, 21 May 2017 at 10:03:58 UTC, Nicholas Wilson wrote:
> As in the function signature of the function you call `ok` or 
> `error` in.
>
> Result!(int, SomeEnum) myfunc(bool foo)
> {
>     if(!foo)
>         return ok(42);
>     else
>         return error(SomeEnum.fooHappened);
> }
>
> should work.

This is what I've got right now.

--- [module 1]
struct Result(OkType, ErrType)
{
     this(OkType ok) pure nothrow
     {
         isOk = true;
         okPayload = ok;
     }

     this(ErrType error) pure nothrow
     {
         isOk = false;
         errorPayload = error;
     }

     bool isOk;

     union
     {
         OkType okPayload;
         ErrType errorPayload;
     }
}

auto ok(T, E)(T payload) { return Result!(T, E)(payload); }
auto error(T, E)(T payload) { return Result!(T, E)(payload); }

--- [module 2]

Result!(string, int) fn(bool shouldErr) {
     if (!shouldErr)
	return ok("No problem");
     return error(0);
}

---

But it can't infer the second parameter.
"template result.ok cannot deduce function from argument types 
!()(string)"



More information about the Digitalmars-d-learn mailing list