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#
| Name | Description |
|---|---|
is_some | True when this is Some. |
is_none | True when this is None. |
unwrap_or | The value, or fallback when None. |
unwrap_or_else | The value, or the result of f when None. |
map | Some(f(value)), or None. |
map_or | f(value), or fallback when None. |
and_then | f(value) (itself an Option), or None. |
or | This option if it is Some, otherwise other. |
or_else | This option if it is Some, otherwise the result of f. |
filter | This option if its value passes pred, otherwise None. |
ok_or | Ok(value), or Err(err) when None. |
Trait implementations#
ArbitraryforOption<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#
Vec::popVec::removeResult: The outcome of an operation that can fail:Ok(value)orErr(error).