LEARN VOID / 08
Results & errors
Make recoverable outcomes explicit.
Represent success and failure with results, then handle both cases.
func divide(value: i32) -> result<i32, string>:
if value == 0:
return Err("division by zero")
return Ok(100 / value)
func entry(value: i32) -> i32:
var outcome = divide(value)
return match outcome:
Ok(var number): number
Err(var reason): -1Input 2Expected result 50
Return success or failure
result<i32, string> carries either an integer success value or a string error. Ok constructs success and Err constructs a recoverable failure.
Handle both cases
match selects the corresponding branch. var number captures the success value; var reason captures the error. Input 2 returns 50, while zero returns -1 through the error branch.
Propagate when appropriate
Inside a compatible result-returning function, ? unwraps success or returns the matching error to its caller. Recoverable results remain distinct from runtime failures such as invalid indexing or a failed checked conversion.