Result Type
Result[T, E] represents either a successful value or an error. It replaces exceptions in other languages.
Definition
type Result[T, E] =
| Ok(T)
| Err(E)Creating Results
let success: Result[i32, string] = Ok(42)
let failure: Result[i32, string] = Err("Something went wrong")Working with Results
Pattern Matching
fn divide(a: i32, b: i32) -> Result[i32, string] {
if b == 0 {
return Err("Division by zero")
}
return Ok(a / b)
}
effect fn main() -> void {
match divide(10, 2) {
Ok(n) => { std.io.println("Result: " + to_string(n)) }
Err(e) => { std.io.println("Error: " + e) }
}
}The Try Operator (?)
In effect functions returning Result, use ? to propagate errors:
effect fn process() -> Result[i32, string] {
let a: i32 = divide(10, 2)? // Propagates Err if division fails
let b: i32 = divide(a, 2)? // Propagates Err if this fails
return Ok(b)
}The ? operator:
- If the result is
Ok(value), extracts the value - If the result is
Err(e), immediately returnsErr(e)from the enclosing function
Standard Library Functions
The std.result module provides utilities for working with results:
import std.result
let is_ok: bool = std.result.is_ok(result)
let is_err: bool = std.result.is_err(result)See Standard Library Overview for more details.