Result Types
Note: Not built: a throws signature, throw, a plain value returned where a Result is expected, and the ? and || operators.
Result is an enum#
Core declares enum Result[T, E] {Ok(T); Error(E);}: each is a variant declared as a type, holding its value with no field name, and a pattern that binds one, case imm n Ok, gives that value itself. A Result is built, passed, returned and matched like any enum, and its variants, Ok and Error, are names in every module.
Results and throws#
In our earlier discussion about exception handling, we introduced the idea that some functions can choose to throw an exception value on failure and a regular value on success. This is actually just a Result value being returned. Built-in language syntax just makes it clearer and simpler to work with such values:
- A function whose return signature is i32 throws bool is another way to write a Result type: Result[i32, bool]
- return 3 is equivalent to return Ok(3).
- throw false is equivalent to return Error(false).
The ? and || operators#
The ? operator (try) and || operator (or else) offer more concise and readable ways to perform various common patterns for applying pattern matching blocks against a Result value.