Result and try
Propagating errors with try, terminating with match.
enum Result[T, E]: case Ok(value: T) case Err(error: E)
def read(ok: bool) -> Result[i32, bool]: if ok: return Ok(value=42) else: return Err(error=true)
def close(ok: bool) -> Result[None, bool]: if ok: return Ok(value=None) else: return Err(error=true)
def compute(ok: bool) -> Result[i32, bool]: try close(true) let value: i32 = try read(ok) return Ok(value=value)
def main() -> i32: let result: Result[i32, bool] = compute(true) let code: i32 = match result: Ok(value) => value Err(error) => 1 return codeWhat’s worth noticing:
try close(true):tryin statement position. TheOkpayload here isNone, so the value is discarded; anErrwould causecomputeto return early with the sameErr.let value: i32 = try read(ok):tryin expression position. OnOk(v), evaluates tov. OnErr(e), the function returnsErr(error=e)immediately.match result:is used at the top level inmain: once you’re at the program boundary,tryno longer makes sense (there’s no outer function to propagate to). Match terminates the chain.- The two
trysites both produceResult[_, bool]:tryrequires the result’sEto match the surrounding function’sE.
For the helpers (is_ok, unwrap_or), see std.result.