v0.4.0
Errors · Lesson 9.4

Outcome

Source
Keep an outcome that must outlive its call in Core's Result<T, E>, then store, pass, build and match it through .Success and .Failure.
You'll need: Fail, Match expression

A call that can throw is handled right where it is made, so it usually leaves nothing to keep. Sometimes, though, an outcome has to outlive the call: it is stored in a variable, passed to a function and looked at later. That outcome is one value that is either a success or a failure, and Core's Result<T, E> holds one.

Result is an ordinary variant

Result is not built into the language. It is a plain variant in the Core package:

variant Result<T, E> {
    Success(T),
    Failure(E)
}

It has no special support from the compiler, so it is used like any other variant: imported with import Core::Result;, matched with match, and built with its two cases. The lesson's Rux.toml lists Core under [Dependencies] for that import.

From a call to a stored outcome

A throwing call gives its success, not a Result, so the outcome is made explicitly. try ... catch wraps both channels:

func Keep(slices: int, people: int) -> Result<int, NobodyToShare> {
    return try .Success(Share(slices, people)) catch { e => .Failure(e) };
}

On success, Share's value is wrapped in .Success. On failure, the catch arm wraps the error in .Failure. The return type tells both cases which variant they belong to, so neither needs Result:: written.

Store first, look later

Each call's outcome is stored first and examined afterwards:

let party = Keep(12, 4);
let empty = Keep(12, 0);
Describe(party);
Describe(empty);

Describe takes the outcome as a parameter like any other value:

func Describe(outcome: Result<int, NobodyToShare>) {

Patterns look inside

.Success(...) and .Failure(...) are the two shapes a result can have. In a match they are patterns, and whatever is written inside the parentheses is matched against the payload — a name binds it, a literal compares it, _ ignores it:

match outcome {
    .Success(0) => PrintLine("not even one slice each"),
    .Success(each) => PrintLine("{} slices each", each),
    .Failure(error) => PrintLine("{} slices and nobody to eat them", error.slices)
}
PatternMatchesBinds
.Success(0)a success whose value is 0nothing
.Success(each)any successthe value
.Failure(error)any failurethe error
.Failure(_)any failurenothing

Order matters, as in every match: .Success(0) comes before .Success(each), because the first arm that matches wins and the general arm would otherwise take the zero too.

Building a result by hand

Outside a match, the same two shapes are constructors. No function needs to be called:

let promised: Result<int, NobodyToShare> = .Success(2);
let refused: Result<int, NobodyToShare> = .Failure(NobodyToShare { slices: 8 });

The type annotation is required. .Success(2) names a case, but on its own it does not say which variant the case belongs to, or what the other case would have held.

A match that produces a value

A match on a result can be an expression, with one value per shape:

let eaten = match party {
    .Success(each) => each * 4,
    .Failure(_) => 0
};

Twelve slices shared among four is three each, so four people eat 12. A match on a result must cover both shapes — a failure can never slip through unnoticed.

The program

The whole lesson is one package in the Examples repository. Its comments explain every step.

Src/Main.rux
// A call that can throw is handled right where it is made, so it usually leaves nothing to keep.
// Sometimes an outcome has to outlive the call: it is stored in a variable, passed to a function
// and looked at later. Core's `Result<T, E>` holds one. It is an ordinary variant,
//
//     variant Result<T, E> { Success(T), Failure(E) }
//
// with no special support from the compiler, so it is used like any other variant.
//
// `try .Success(Share(12, 4)) catch { e => .Failure(e) }` turns a call into a stored outcome:
// the success is wrapped in `.Success`, and the `catch` arm wraps the error in `.Failure`.
// `.Success(...)` and `.Failure(...)` are the two shapes a result can have. In a `match` they are
// patterns, and whatever is written inside the parentheses is matched against the payload — a
// name binds it, a literal compares it. Outside a match they are constructors, so a result can
// also be built by hand, without calling anything.
import Core::Result;
import Io::PrintLine;

struct NobodyToShare {
    slices: int;
}

// Shares out pizza slices evenly. It throws when there is nobody to share them with.
func Share(slices: int, people: int) -> int throws NobodyToShare {
    if people == 0 {
        throw NobodyToShare { slices: slices };
    }
    return slices / people;
}

// Keeps the outcome of one call as a value instead of handling it here.
func Keep(slices: int, people: int) -> Result<int, NobodyToShare> {
    return try .Success(Share(slices, people)) catch { e => .Failure(e) };
}

// A result arrives as a parameter like any other value.
func Describe(outcome: Result<int, NobodyToShare>) {
    match outcome {
        .Success(0) => PrintLine("not even one slice each"),
        .Success(each) => PrintLine("{} slices each", each),
        .Failure(error) => PrintLine("{} slices and nobody to eat them", error.slices)
    }
}

func Main() -> int {
    // Each call's outcome is stored first and examined afterwards.
    let party = Keep(12, 4);
    let empty = Keep(12, 0);
    Describe(party);
    Describe(empty);
    Describe(Keep(3, 4));

    // The same two shapes as constructors. The type annotation says which result is meant.
    let promised: Result<int, NobodyToShare> = .Success(2);
    let refused: Result<int, NobodyToShare> = .Failure(NobodyToShare { slices: 8 });
    Describe(promised);
    Describe(refused);

    // A match can also produce a value, one per shape.
    let eaten = match party {
        .Success(each) => each * 4,
        .Failure(_) => 0
    };
    PrintLine("eaten at the party: {}", eaten);

    // A match on a result must cover both shapes. Drop the `.Failure` arm above and the compiler
    // refuses: "match on 'Result<int, NobodyToShare>' is not exhaustive; missing Result::Failure".
    // A failure can never slip through unnoticed.
    return 0;
}

Besides Io, its Rux.toml lists Core under [Dependencies].

Run it

cd Examples/Errors/Outcome
rux run
3 slices each
12 slices and nobody to eat them
not even one slice each
2 slices each
8 slices and nobody to eat them
eaten at the party: 12

Common mistakes

Try it yourself

  1. Add an arm that prints "exactly one slice each". Where in the match must it go?
  2. Build a result by hand with .Failure(NobodyToShare { slices: 0 }) and pass it to Describe.
  3. Store Keep(7, 2) in a variable, then use one match expression to work out how many slices are eaten and another to print it.

Learn more