Sub topic 8
Moving between Option and Result
This chapter assumes you know how Option<T> and Result<T, E> are defined, how to handle them with match, if let, and let else, and how closures work. It covers the methods that convert one type into the other, and when each conversion is the right choice.
Why convert at all
Option<T> says a value is absent but not why. Result<T, E> says an operation failed and carries the reason. Real code uses both, often in the same function. A map lookup returns an Option, and parsing the value you found returns a Result. To combine them you convert one into the other.
Each conversion either adds information (a reason for absence) or removes it (the error). The table lists the main methods.
| Method | From | To | Effect |
|---|---|---|---|
| `ok_or(e)` | `Option<T>` | `Result<T, E>` | `None` becomes `Err(e)` |
| `ok_or_else(f)` | `Option<T>` | `Result<T, E>` | `None` becomes `Err(f())`, computed only when needed |
| `ok()` | `Result<T, E>` | `Option<T>` | `Err` becomes `None`, the error is dropped |
| `err()` | `Result<T, E>` | `Option<E>` | `Ok` becomes `None`, the error is kept |
| `transpose()` | `Option<Result<T, E>>` | `Result<Option<T>, E>` | swaps the two layers |
From Option to Result: ok_or and ok_or_else
ok_or maps Some(v) to Ok(v) and None to Err(e), where you supply e.
use std::collections::HashMap;
fn main() {
let mut ages: HashMap<&str, u32> = HashMap::new();
ages.insert("ana", 31);
let eager: Result<u32, String> = ages.get("bo").copied().ok_or(String::from("unknown"));
let lazy: Result<u32, String> = ages
.get("bo")
.copied()
.ok_or_else(|| format!("no entry for {}", "bo"));
println!("{eager:?}");
println!("{lazy:?}");
}This prints Err("unknown") and then Err("no entry for bo").
The difference between the two methods is when the error is built. ok_or takes a value, so Rust builds the error before the call, even when the option is Some and the error is thrown away. ok_or_else takes a closure that runs only for None.
From Result to Option: ok and err
ok() turns Ok(v) into Some(v) and Err(_) into None. It fits when failure only means "no usable value" and the cause does not matter.
fn main() {
let a: Option<u16> = "443".parse::<u16>().ok();
let b: Option<u16> = "http".parse::<u16>().ok();
println!("{a:?} {b:?}");
let r: Result<u8, String> = Err("boom".to_string());
println!("{:?}", r.err());
}This prints Some(443) None, then Some("boom"). The err() method is the mirror image. It is rarely needed, but it is useful for collecting only the failures.
A common use of ok() is filter_map, which keeps the values that parsed and skips the rest.
fn main() {
let items = ["1", "two", "3"];
let nums: Vec<i32> = items.iter().filter_map(|s| s.parse().ok()).collect();
println!("{nums:?}");
}The output is [1, 3]. The word "two" disappears with no message.
Combining a lookup with a parse
A typical case is a configuration lookup, which returns an Option, followed by a parse, which returns a Result. Convert the Option first so the whole function uses one error type.
use std::collections::HashMap;
fn port_from_env(vars: &HashMap<&str, &str>) -> Result<u16, String> {
let raw = vars
.get("PORT")
.ok_or_else(|| String::from("PORT not set"))?;
raw.parse::<u16>()
.map_err(|e| format!("PORT invalid: {e}"))
}
fn main() {
let good = HashMap::from([("PORT", "8080")]);
let bad = HashMap::from([("PORT", "http")]);
let empty: HashMap<&str, &str> = HashMap::new();
println!("{:?}", port_from_env(&good));
println!("{:?}", port_from_env(&bad));
println!("{:?}", port_from_env(&empty));
}The output is:
Ok(8080)
Err("PORT invalid: invalid digit found in string")
Err("PORT not set")Here ok_or_else supplies the reason for absence, and ? returns early on that Err. map_err changes the parse error into the same String type. Both branches now produce Result<u16, String>.
The ? operator does not mix the two types
The ? operator works on Option in a function that returns Option, and on Result in a function that returns Result. It does not convert across the two. This function does not compile:
fn port_or_none(s: &str) -> Option<u16> {
let p = s.trim().parse::<u16>()?; // error: `?` on a Result in a function returning Option
Some(p)
}The fix is to convert first. Calling .ok() before ? turns the Result into an Option.
fn port_or_none(s: &str) -> Option<u16> {
let p = s.trim().parse::<u16>().ok()?;
Some(p)
}
fn first_word_len(text: Option<&str>) -> Option<usize> {
let t = text?;
let w = t.split_whitespace().next()?;
Some(w.len())
}
fn main() {
println!("{:?}", port_or_none(" 80 "));
println!("{:?}", port_or_none("eighty"));
println!("{:?}", first_word_len(Some("hello world")));
println!("{:?}", first_word_len(Some(" ")));
}This prints Some(80), None, Some(5), and None. The reverse direction needs the same care. In a function returning Result, write option.ok_or(...)?. A bare option? is rejected because a None has no error value to return.
Swapping layers with transpose
Sometimes the nesting is in the wrong order. An optional input that you parse gives Option<Result<T, E>>: "maybe there is a value, and if so it may be invalid". You usually want Result<Option<T>, E>: "either the input was invalid, or I have maybe a value". The transpose method swaps the two layers.
use std::num::ParseIntError;
fn parse_optional(s: Option<&str>) -> Result<Option<u16>, ParseIntError> {
s.map(|t| t.parse::<u16>()).transpose()
}
fn main() {
println!("{:?}", parse_optional(Some("80")));
println!("{:?}", parse_optional(None));
println!("{:?}", parse_optional(Some("x")));
}The output is:
Ok(Some(80))
Ok(None)
Err(ParseIntError { kind: InvalidDigit })
</parameter>I need to correct that: the last block above must be closed properly.
Ok(Some(80))
Ok(None)
Err(ParseIntError { kind: InvalidDigit })A missing optional setting is not an error here (Ok(None)), but a present and malformed one is (Err). Once the types are flipped, ? can unwrap the Result layer and leave you with a plain Option to handle.
Choosing a conversion
- Use
ok_ororok_or_elsewhen absence is a failure the caller must know about. - Use
ok()when the reason for failure does not matter andNoneis a sufficient answer. - Use
transposewhen an optional input might be malformed and you want to tell "not given" apart from "given but invalid". - Keep the function's return type as the guide. If it returns
Result, convertOptions intoResults. If it returnsOption, convertResults withok().
Exercise
What does Some(3).ok_or("missing") evaluate to, and what does None::<i32>.ok_or("missing") evaluate to?
Show answer
The first is Ok(3) and the second is Err("missing"). Both have type Result<i32, &str>.
Exercise
A function returns Option<u16> and its body contains let p = s.parse::<u16>()?;. Why does this fail to compile, and how do you fix it?
Show answer
The ? operator on a Result needs the enclosing function to return a compatible Result, and there is no conversion from an error to None. Convert first with ok(): let p = s.parse::<u16>().ok()?;.
Exercise
Given let input: Option<&str> = Some("12x");, which expression produces Err(...) and why: input.map(|t| t.parse::<u16>()).transpose() or input.and_then(|t| t.parse::<u16>().ok())?
Show answer
The first. It yields Err(ParseIntError { .. }) because transpose keeps the parse error. The second returns None because ok() drops the error.