In Rust, how do Option::ok_or, ok_or_else and Result::ok convert between Option and Result, and why prefer ok_or_else?
answer
- one goes up, one goes down
- arguments run before the call
- a closure runs only on None
- ok() drops the error
basics
~10 sOption::ok_or(e) and ok_or_else(f) turn Some(v) into Ok(v) and None into Err; Result::ok() turns Ok(v) into Some(v) and drops the error. ok_or_else builds the error lazily, only when the Option is None.
solid answer
~40 s`Option::ok_or(err)` maps `Some(v)` to `Ok(v)` and `None` to `Err(err)`; `ok_or_else(f)` does the same but calls `f` only on `None`. Because Rust evaluates a function's arguments before the call, `users.get(&id).ok_or(format!("user {id} not found"))` allocates that `String` even when the user exists; std's own doc comment recommends `ok_or_else` when you are passing the result of a function call. The same eager-versus-lazy pair exists for `unwrap_or` and `unwrap_or_else`, with `unwrap_or_default` when `T: Default`. Going the other way, `Result::ok()` turns `Ok(v)` into `Some(v)` and discards the error, and `Result::err()` keeps only the error. Use `ok()` only when the reason truly does not matter, because it is gone afterwards.
code
rust · 22 linesuse std::collections::HashMap;
fn not_found(id: u64) -> String {
println!(" building error for {id}");
format!("user {id} not found")
}
fn main() {
let users: HashMap<u64, String> = HashMap::from([(7, "41".to_string())]);
// ok_or: the argument is evaluated before the call, even when the user exists
let a: Result<&String, String> = users.get(&7).ok_or(not_found(7));
// ok_or_else: the closure runs only on None
let b: Result<&String, String> = users.get(&7).ok_or_else(|| not_found(7));
let c: Result<&String, String> = users.get(&9).ok_or_else(|| not_found(9));
println!("a={a:?} b={b:?} c={c:?}");
// ok() and err() go back to Option, discarding the other side
let age: Option<u32> = "4x".parse::<u32>().ok();
let why = "4x".parse::<u32>().err().map(|e| e.to_string());
println!("age={age:?} why={why:?}");
}go deeper
Recall the direction of each method: ok_or and ok_or_else go from Option to Result, ok and err go from Result to Option.
Explain eager versus lazy: arguments are evaluated before the call, so ok_or builds its error every time and ok_or_else only on None.
Catch costly eager arguments in review, and push back on .ok() where a failure's reason should reach a log or a user.
Treat lossy conversions as a team convention question: where in the call stack may an error's reason be dropped, and who decides.
## The four conversions Code often holds one of the two types and needs the other: a lookup returns `Option`, but the surrounding function reports failures as `Result`; or a parse returns `Result`, but the caller only cares whether a number came out. Std provides a method for each direction: | Method | From | To | What happens to the empty side | |---|---|---|---| | `Option::ok_or(err)` | `Option<T>` | `Result<T, E>` | `None` becomes `Err(err)`; `err` is built before the call | | `Option::ok_or_else(f)` | `Option<T>` | `Result<T, E>` | `None` becomes `Err(f())`; `f` runs only on `None` | | `Result::ok()` | `Result<T, E>` | `Option<T>` | the error value is dropped | | `Result::err()` | `Result<T, E>` | `Option<E>` | the success value is dropped | `ok()` and `err()` consume the `Result`. To inspect a `Result` you still need afterwards, borrow it first: `r.as_ref().ok()` gives `Option<&T>`. ## Eager versus lazy arguments Rust evaluates every argument expression **before** the method runs. `ok_or` therefore receives an already-built error value, whether or not the `Option` turns out to be `None`. The doc comment on `Option::ok_or` in core says it directly: arguments passed to `ok_or` are eagerly evaluated, and if you are passing the result of a function call, it is recommended to use `ok_or_else`, which is lazily evaluated. In the user-lookup scenario: ```rust let a = users.get(&7).ok_or(not_found(7)); // not_found runs even though user 7 exists let b = users.get(&7).ok_or_else(|| not_found(7)); // not_found does not run ``` If `not_found` formats a `String`, logs, or bumps a metric, the eager form does that work on every successful lookup, and a log line saying "building error" appears for a user that was found. The same split appears across the API: - `unwrap_or(default)` versus `unwrap_or_else(|| compute())` for supplying a fallback value. - `or(other)` versus `or_else(|| other())` for supplying a fallback `Option` or `Result`. - `map_or(default, f)` versus `map_or_else(default_fn, f)`. - `unwrap_or_default()` when the fallback is simply `T::default()` and `T: Default`. The eager forms are not wrong. When the argument is a constant, a literal, a unit-like error variant or a value already computed, there is nothing to defer, and `ok_or(Error::NotFound)` reads more simply than a closure. ## What ok() throws away `Result::ok()` is the lossy direction. Parsing an age with `"4x".parse::<u32>().ok()` gives `None`, and the fact that the input contained an invalid digit is gone. That is acceptable when the caller genuinely treats every failure the same way, for example ignoring malformed optional hints. It is a defect when the failure should be logged or shown to a user: 1. Decide whether any caller will need the reason. 2. If yes, keep the `Result` and transform the error with `map_err` instead of dropping it. 3. If no, convert with `ok()` at the last possible point, so the reason survives as long as possible. `err()` is the mirror image and is useful mainly for collecting or counting failures, for example `results.iter().filter_map(|r| r.as_ref().err())`. ## Common mistakes - Passing `format!(...)` or a logging call to `ok_or` or `unwrap_or`, paying for it on every success. - Believing `ok_or` skips evaluating its argument on `Some`; only the `_else` variants defer work. - Calling `.ok()` to silence a `#[must_use]` warning, which throws away the error instead of handling it. - Forgetting that `ok()` consumes the `Result`: unless both `T` and `E` are `Copy`, using the original afterwards fails with E0382, borrow of moved value. Propagating the converted `Result` out of a function with the question-mark operator is that operator's own lesson; these methods are what make an `Option` fit a `Result`-returning function in the first place.
- In Rust, is ok_or ever the better choice over ok_or_else?Yes, when the error value is cheap and already known: a unit-like enum variant, a `&'static str`, a copied integer. Nothing is deferred by a closure in that case, so `ok_or(Error::NotFound)` is simpler to read. Switch to `ok_or_else` once building the error allocates, formats, logs or calls a function.
- How do you get an Option from a Rust Result without consuming the Result?Borrow first: `r.as_ref().ok()` turns `&Result<T, E>` into `Result<&T, &E>` and then into `Option<&T>`, leaving `r` usable. `r.as_ref().err()` does the same for the error side. Calling `r.ok()` directly moves `r`.
- ok_or only evaluates its argument when the Option is None
- Result::ok() keeps the error somewhere so it can be recovered later
- ok_or_else is always better, even for a constant error value
- Calling .ok() is a good way to handle a must-use Result warning
- unwrap_or_else and unwrap_or differ in the type they return