Rust Reference ยท Option and Result
Option filter, or, xor and and
Reference for combining Option values in Rust: filter, or, or_else, xor, and, get_or_insert_with and insert, with examples of choosing between two optional values.
These methods combine or restrict Option values without unpacking them. filter keeps a Some only if its value passes a test. or and or_else pick a fallback option when the first is None. xor accepts exactly one of two. and returns the second option only if the first is Some.
They are the option equivalents of boolean logic and are handy for configuration lookups ("command-line flag, else environment variable, else default") and validation.
Some(4).filter(|n| n % 2 == 0); // Some(4) None.or(Some(9)); // Some(9)
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
impl<T> Option<T> { pub fn filter<P: FnOnce(&T) -> bool>(self, predicate: P) -> Option<T>; pub fn or(self, optb: Option<T>) -> Option<T>; pub fn or_else<F: FnOnce() -> Option<T>>(self, f: F) -> Option<T>; pub fn xor(self, optb: Option<T>) -> Option<T>; pub fn and<U>(self, optb: Option<U>) -> Option<U>; pub fn get_or_insert_with<F: FnOnce() -> T>(&mut self, f: F) -> &mut T; pub fn insert(&mut self, value: T) -> &mut T; }
| Method | Result |
|---|---|
filter(p) |
Some(x) if self is Some(x) and p(&x), otherwise None. |
or(b) |
self if it is Some, else b. |
or_else(f) |
self if Some, else f(). |
xor(b) |
Some only when exactly one of self and b is Some. |
and(b) |
b if self is Some, else None. The first value is dropped. |
get_or_insert_with(f) |
Stores f() if None, then returns &mut T. |
Returns: an Option, except the two in-place methods that return &mut T.
Usage notes
oris eager. The argument is built even when unused; useor_elseif building it costs something, like an environment lookup or allocation.filterhands the predicate a reference (&T), so write|n| *n > 3or rely on auto-deref for methods like|s| !s.is_empty().xoris rare. It fits "exactly one of these two settings must be given" checks.anddiscards the first value and exists mostly for symmetry; for real chains useand_then.- Fallback chains read well in a row:
cli.or(env).or(file).unwrap_or(default). - Caching pattern.
get_or_insert_withavoids amatchwhen lazily filling a field; the returned&mut Tborrows the option for as long as you use it. - Eager sibling.
get_or_insert(value)does the same with a ready value, evaluated even when not needed.