Result
enum Result<T, E>
Source: compiler/src/builtin_docs/prelude.hy The outcome of an operation that can fail: Ok(value) or Err(error).
Result is auto-imported into every file. Construct it with
Result::Ok(x) and Result::Err(e); bare Ok / Err also work while no
other enum in scope has a case with the same name.
A function annotated -> Result<T, E>, or one that uses raise or ? on
a Result, runs in result mode: a plain return v; is wrapped as Ok(v)
and raise e; returns Err(e). x? unwraps Ok or returns the Err
early. x ?? default unwraps Ok or falls back to default, silently
discarding the error, so prefer match or ? when the failure matters.
Variants#
Ok(T)#
The operation succeeded with a value of type T.
Err(E)#
The operation failed with an error of type E.
Methods#
| Name | Description |
|---|---|
is_ok | True when this is Ok. |
is_err | True when this is Err. |
ok | The Ok value as an Option. |
err | The Err value as an Option. |
unwrap_or | The Ok value, or fallback on Err. |
unwrap_or_else | The Ok value, or f applied to the error. |
map | Ok(f(value)), or the same error. |
map_err | The same value, or Err(f(error)). |
and_then | f(value) (itself a Result), or the same error. |
or_else | This result if it is Ok, otherwise f(error). |
Examples#
use tests::assert;
fn half(int n) -> Result<int, string> {
if n % 2 != 0 {
raise "odd";
}
return n / 2;
}
fn main() {
let ok = match half(10) {
Result::Ok(v) => v,
Result::Err(_) => 0,
};
assert!(ok == 5);
let msg = match half(3) {
Result::Ok(_) => "",
Result::Err(e) => e,
};
assert!(msg == "odd");
}
See also#
Option: An optional value: eitherSome(value)orNone.