std.optional

Standard-library module std.optional.

Importuse std.optional

Functions

fn map<T, U>(value: Optional<T>, f: fn(T) -> U) -> Optional<U>#

Applies f to a present value; absent stays absent.

  • value: The optional to map.
  • f: Applied to the present value.
println(some(2).map(|x| x * 10)) // some(20)
fn or<T>(value: Optional<T>, other: Optional<T>) -> Optional<T>#

The value when present, otherwise other.

  • value: The preferred optional.
  • other: Used when value is absent.
let absent: Optional<int> = none
println(absent.or(some(9))) // some(9)
fn or_else<T>(value: Optional<T>, f: fn() -> Optional<T>) -> Optional<T>#

The value when present, otherwise whatever f produces.

  • value: The preferred optional.
  • f: Called only when value is absent.
fn unwrap_or_else<T>(value: Optional<T>, f: fn() -> T) -> T#

The present value, otherwise the result of calling f.

  • value: The optional to unwrap.
  • f: Called only when value is absent.
let absent: Optional<int> = none
println(absent.unwrap_or_else(|| 7)) // 7
fn ok_or<T>(value: Optional<T>, failure: Error) -> Result<T, Error>#

Turns a present value into ok, and absence into the given error.

  • value: The optional to convert.
  • failure: The error carried when value is absent.
let absent: Optional<int> = none
let missing: Result<int, Error> = err.NotFound("no such item")
println(absent.ok_or(missing.unwrap_err()).is_err()) // true
fn filter<T>(value: Optional<T>, predicate: fn(T) -> bool) -> Optional<T>#

Keeps a present value only when predicate accepts it.

  • value: The optional to test.
  • predicate: Applied to the present value.
println(some(4).filter(|x| x > 3)) // some(4)
println(some(2).filter(|x| x > 3)) // none
fn flatten<T>(value: Optional<Optional<T>>) -> Optional<T>#

Removes one level of nesting.

  • value: An optional whose payload is itself optional.
let nested: Optional<Optional<int>> = some(some(1))
println(nested.flatten()) // some(1)