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.
let port: Option<u16> = None; let r: Result<u16, String> = port.ok_or("missing port".to_string()); // Err("missing port")
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 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 theStringon every call, even forSome. Preferok_or_else(|| format!("..."))for anything that allocates. For a plain enum variant or a&'static str,ok_oris fine and clearer. - Clippy hint: the
or_fun_calllint flags function calls passed took_or. Switch took_or_elsewhen it fires. - Typical pattern:
map.get(key).ok_or(MyError::NotFound)?orargs.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 anOption. - Borrowed contents: use
as_ref()first if you still need the option afterwards, becauseok_orconsumes it. - Failing with a message at the top level is often written
.ok_or("...")?combined withBox<dyn Error>as the function's error type, since&strconverts into it.