Enum in prelude auto-imported

Option

enum Option<T>
Source: compiler/src/builtin_docs/prelude.hy

An optional value: either Some(value) or None.

Option is auto-imported into every file. Construct it with Option::Some(x) and Option::None; bare Some / None also work while no other enum in scope has a case with the same name.

Take it apart with match, the coalesce operator ?? (use a default when the value is None), the try operator ? (return None early from a function that itself returns an Option) or optional access a?.field. Vec::pop and Vec::remove return Option.

Variants#

None#

No value.

Some(T)#

Some value of type T.

Methods#

NameDescription
is_someTrue when this is Some.
is_noneTrue when this is None.
unwrap_orThe value, or fallback when None.
unwrap_or_elseThe value, or the result of f when None.
mapSome(f(value)), or None.
map_orf(value), or fallback when None.
and_thenf(value) (itself an Option), or None.
orThis option if it is Some, otherwise other.
or_elseThis option if it is Some, otherwise the result of f.
filterThis option if its value passes pred, otherwise None.
ok_orOk(value), or Err(err) when None.

Trait implementations#

  • Arbitrary for Option<T: Arbitrary>

Examples#

use tests::assert;
fn find(Vec<int> xs, int wanted) -> Option<int> {
    let i = 0;
    while i < xs.len() {
        if xs[i] == wanted {
            return Option::Some(i);
        }
        i = i + 1;
    }
    return Option::None;
}

fn main() {
    let xs: Vec<int> = [4, 8, 15];
    let at = match find(xs, 8) {
        Option::Some(i) => i,
        Option::None => -1,
    };
    assert!(at == 1);
    assert!((find(xs, 99) ?? -1) == -1);
}

See also#

↑ ↓ navigate ↵ open