Sub topic 8
Moving between Option and Result
This chapter assumes you can write match on Option and Result, and that you know closures and the basic combinators map and unwrap_or. You will learn how to convert between the two types, and when each conversion loses information.
Why convert
Option<T> says a value may be missing. Result<T, E> says an operation may fail, and it carries the reason. A function often receives one and must return the other. For example, a lookup returns Option, but your function reports errors with Result. Converting lets you keep one error style inside a function.
Option to Result: ok_or and ok_or_else
ok_or turns Some(v) into Ok(v) and None into Err(e). You supply the error.
fn find_user(id: u32) -> Option<&'static str> {
match id {
1 => Some("ada"),
2 => Some("grace"),
_ => None,
}
}
fn user_or_error(id: u32) -> Result<&'static str, String> {
find_user(id).ok_or(format!("no user with id {id}"))
}
fn user_or_error_lazy(id: u32) -> Result<&'static str, String> {
find_user(id).ok_or_else(|| format!("no user with id {id}"))
}
fn main() {
println!("{:?}", user_or_error(1));
println!("{:?}", user_or_error(9));
println!("{:?}", user_or_error_lazy(9));
}ok_or evaluates its argument every time, even when the value is Some. Here that means format! allocates a string that is thrown away on success. ok_or_else takes a closure and runs it only on None. Use ok_or for cheap values such as an enum variant, and ok_or_else when building the error costs something.
Result to Option: ok and err
ok() turns Ok(v) into Some(v) and Err(_) into None. err() does the opposite. Both discard the other side.
fn main() {
let good: Result<i32, String> = Ok(5);
let bad: Result<i32, String> = Err(String::from("boom"));
println!("{:?} {:?}", good.clone().ok(), good.clone().err());
println!("{:?} {:?}", bad.clone().ok(), bad.clone().err());
}Use ok() only when the reason for failure does not matter. A common case is "80x".parse::<u16>().ok(), where you only want to know whether parsing worked.
Summary of the conversions
| Method | From | To | What is lost |
|---|---|---|---|
| `ok_or(e)` | `Option<T>` | `Result<T, E>` | Nothing. You add an error. |
| `ok_or_else(f)` | `Option<T>` | `Result<T, E>` | Nothing. The error is built lazily. |
| `ok()` | `Result<T, E>` | `Option<T>` | The error value |
| `err()` | `Result<T, E>` | `Option<E>` | The success value |
Converting and then using ?
The ? operator works on Option in functions that return Option, and on Result in functions that return Result. It does not mix them. If a function returns Result and you hold an Option, convert first.
fn first_word_len(text: &str) -> Result<usize, &'static str> {
let word = text.split_whitespace().next().ok_or("empty input")?;
Ok(word.len())
}
fn main() {
println!("{:?}", first_word_len("hello world"));
println!("{:?}", first_word_len(" "));
}Writing .next()? here would not compile, because the function returns Result and None has no error to put in it.
Exercise
A function returns Result<u16, String>. Inside it you call map.get("port"), which returns Option<&String>. Which method do you chain so you can use ? on it, and which variant should you pick if building the error message calls format!?
Show answer
Chain ok_or_else, for example map.get("port").ok_or_else(|| format!("missing key: port"))?. It builds the error string only when the key is missing. ok_or would run format! on every call, including successful ones.
Exercise
What does "abc".parse::<i32>().ok() return, and what information is gone?
Show answer
It returns None. The ParseIntError that explained the failure (an invalid digit) is discarded.