Result

This is a subset of functions available in the official reference for working with Result variants. See this chapter of this book for more information on Result.

The convention is to name the module alias after the file name it is defined in:

import Result "mo:base/Result";

On this page

Public type Result<Ok, Err>

Function fromOption
Function toOption
Function isOk
Function isErr

Public type

The Result<Ok, Err> type is a variant with two generic parameters. It can be used as the return type for functions to indicate either success or error. Both cases can be handled programmatically.

type Result<Ok, Err> = { #ok : Ok; #err : Err }

A Result<Ok, Err> could either be

We usually import, rename and instantiate Result with types for our own purpose and use it as the return type of a function.

import Result "mo:base/Result";

type MyResult = Result.Result<Nat, Text>;

func doSomething(b : Bool) : MyResult {
    switch (b) {
        case true #ok(0);
        case false #err("false");
    };
};

switch (doSomething(true)) {
    case (#ok(nat)) {};
    case (#err(text)) {};
};

We import Result and declare our own custom type MyResult by instantiating the Result<Ok, Err> with types Nat and Text.

Our function doSomething could either return a #ok with a Nat value or a #err with a Text value.

Both cases are handled programmatically in the last switch expression. The return values associated with both cases are locally named nat and text and could be used inside the switch case body.

Result.fromOption

func fromOption<R, E>(x : ?R, err : E) : Result<R, E>
import Result "mo:base/Result";

Result.fromOption<Nat, Text>(?100, "error")

Result.toOption

func toOption<R, E>(r : Result<R, E>) : ?R
import Result "mo:base/Result";

let ok : Result.Result<Nat, Text> = #ok 100;

let opt : ?Nat = Result.toOption(ok);

Result.isOk

func isOk(r : Result<Any, Any>) : Bool
import Result "mo:base/Result";

let ok : Result.Result<Nat, Text> = #ok 100;

Result.isOk(ok);

Result.isErr

func isErr(r : Result<Any, Any>) : Bool
import Result "mo:base/Result";

let err : Result.Result<Nat, Text> = #err "this is wrong";

Result.isErr(err);