Sub topic 8
Moving between Option and Result with ok_or and ok_or_else
This chapter assumes you know Result, Option, and the basic ? operator on each. It also assumes you can read closures such as || value.
Why you need to convert
? works on one type per function. In a function that returns Result, you can't write ? on an Option, because the compiler has no error value to return for None. The fix is to turn the Option into a Result first. ok_or and ok_or_else do that. You choose the error value for the None case.
ok_or and ok_or_else
Option<T>::ok_or(err) returns Ok(v) for Some(v) and Err(err) for None.
fn main() {
let some: Option<i32> = Some(3);
let none: Option<i32> = None;
println!("{:?}", some.ok_or("nothing there"));
println!("{:?}", none.ok_or("nothing there"));
}This prints Ok(3) and then Err("nothing there").
The difference between the two methods is when the error value is built:
ok_or(err)buildserrimmediately, even when the option isSome.ok_or_else(|| err)takes a closure. It runs the closure only when the option isNone.
For a string literal, the cost is zero, so ok_or is fine. If building the error allocates, as format! or .to_string() does, use ok_or_else. That way the happy path pays nothing.
Combining with map_err and ?
Real functions often mix both situations. A lookup returns an Option, and a parse returns a Result. Convert each into the same error type, then use ? on both.
use std::collections::HashMap;
fn read_port(config: &HashMap<String, String>) -> Result<u16, String> {
let text = config
.get("port")
.ok_or_else(|| "missing key: port".to_string())?;
let port = text
.parse::<u16>()
.map_err(|e| format!("invalid port {text:?}: {e}"))?;
Ok(port)
}
fn main() {
let mut config = HashMap::new();
println!("{:?}", read_port(&config));
config.insert("port".to_string(), "80x".to_string());
println!("{:?}", read_port(&config));
config.insert("port".to_string(), "8080".to_string());
println!("{:?}", read_port(&config));
}The output is:
Err("missing key: port")
Err("invalid port \"80x\": invalid digit found in string")
Ok(8080)ok_or_else handles the missing key. map_err changes the error type of an existing Result. Both give ? a Result<_, String> to work with.
If your function returns a custom error type with a From implementation, you can skip map_err for errors that already have a From conversion. For example, ParseIntError converts into ConfigError automatically. A missing value still needs ok_or_else, because None carries no error to convert.
Going the other way with ok
Result<T, E>::ok() returns Some(v) for Ok(v) and None for Err(_). It throws the error away.
fn main() {
let good = "42".parse::<i32>().ok();
let bad = "forty-two".parse::<i32>().ok();
println!("{:?} {:?}", good, bad);
}This prints Some(42) None. Use ok() when you only care whether the operation worked, for example inside a ? in a function that returns Option. Don't use it when the caller needs to know why it failed.
Summary of the conversions
| You have | You want | Use | Column | Column |
|---|---|---|---|---|
| `Option<T>` | `Result<T, E>` with a cheap error | `ok_or(err)` | ||
| `Option<T>` | `Result<T, E>` with a costly error | `ok_or_else(\ | \ | err)` |
| `Result<T, E1>` | `Result<T, E2>` | `map_err(f)` or a `From` impl | ||
| `Result<T, E>` | `Option<T>` | `ok()` |
Common mistakes
- Writing
ok_or(|| err)with a closure. This compiles, but it stores the closure as the error value, which is almost never what you want. Closures belong inok_or_else. - Using
ok()and then wondering why the error message is gone.
Exercise
Write a function first_even(items: &[i32]) -> Result<i32, String> that returns the first even number in the slice. If there is none, it returns the error "no even number". Which method do you use to turn the Option from find into a Result, and does the choice between ok_or and ok_or_else matter here?
Show answer
Use items.iter().find(|n| *n % 2 == 0).copied().ok_or("no even number".to_string()), or ok_or_else(|| "no even number".to_string()). The to_string() call allocates, so ok_or_else is better because the allocation happens only when no even number is found. A version that returns Result<i32, &'static str> could use plain ok_or("no even number"), since a literal costs nothing to build.