Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Option and Result

Option ok_or and ok_or_else

Reference for Rust Option::ok_or and ok_or_else: turn None into an error value so you can use the ? operator, with eager versus lazy errors explained.

ok_or converts an Option<T> into a Result<T, E>: Some(v) becomes Ok(v), and None becomes Err(err) using the error you supply. It is the bridge you need when a lookup that may find nothing sits inside a function that reports failures with Result, because the ? operator can only convert an Option to an Option and a Result to a Result.

ok_or_else takes a closure instead of a value, so the error is only built when it is actually needed. Use it whenever creating the error allocates or does real work.

Rust
let port: Option<u16> = None;
let r: Result<u16, String> = port.ok_or("missing port".to_string());
// Err("missing port")

Try it

Rust From None to an error

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.

Rust Using ? after ok_or

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

Rust
impl<T> Option<T> {
    pub fn ok_or<E>(self, err: E) -> Result<T, E>;
    pub fn ok_or_else<E, F: FnOnce() -> E>(self, err: F) -> Result<T, E>;
}
Name Description
err (ok_or) The error value used when the option is None. It is always evaluated, and dropped if unused.
err (ok_or_else) A closure returning the error. It runs only for None.

Returns: Ok(value) for Some(value), Err(error) for None. Both methods consume the option.

Panics: none, unless your closure panics.

Usage notes

  • Eager versus lazy. ok_or(format!("...")) builds the String on every call, even for Some. Prefer ok_or_else(|| format!("...")) for anything that allocates. For a plain enum variant or a &'static str, ok_or is fine and clearer.
  • Clippy hint: the or_fun_call lint flags function calls passed to ok_or. Switch to ok_or_else when it fires.
  • Typical pattern: map.get(key).ok_or(MyError::NotFound)? or args.next().ok_or("missing argument")?.
  • The error type must match the function's error type (or convert into it with From, which ? applies for you). When the error type differs, add .ok_or(...) with the source type, or finish with .map_err(...).
  • The reverse direction is Result::ok(), which discards the error and returns an Option.
  • Borrowed contents: use as_ref() first if you still need the option afterwards, because ok_or consumes it.
  • Failing with a message at the top level is often written .ok_or("...")? combined with Box<dyn Error> as the function's error type, since &str converts into it.