Enum in prelude auto-imported

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#

NameDescription
is_okTrue when this is Ok.
is_errTrue when this is Err.
okThe Ok value as an Option.
errThe Err value as an Option.
unwrap_orThe Ok value, or fallback on Err.
unwrap_or_elseThe Ok value, or f applied to the error.
mapOk(f(value)), or the same error.
map_errThe same value, or Err(f(error)).
and_thenf(value) (itself a Result), or the same error.
or_elseThis 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: either Some(value) or None.
↑ ↓ navigate ↵ open