Sub topic 8
Moving between Option and Result with ok_or and ok_or_else
Functions in real programs often mix Option and Result. A lookup returns Option because "not found" is a normal outcome. The function that called it returns Result because "not found" is a failure there. This chapter shows how to convert between the two so that ? works across the boundary.
This chapter assumes you know the basics of Result, Option, and the ? operator on each, as covered in earlier chapters. It also assumes you can read closures such as || expr.
Why the types don't mix
? works on Option in a function that returns Option. It works on Result in a function that returns Result. It does not cross over. If you write ? on an Option inside a function that returns Result<_, String>, the compiler rejects it with error E0277. The message says the ? operator can only be used on Results, not Options, in a function that returns Result. The reverse case fails the same way.
The reason is that None carries no error value. The From conversion that ? performs needs an error to convert, and None has nothing to give it. You must supply the error yourself, and ok_or and ok_or_else are the methods for that.
ok_or: attach an error to None
Option<T>::ok_or(err) returns Ok(v) for Some(v) and Err(err) for None.
fn first_word(s: &str) -> Result<&str, String> {
s.split_whitespace()
.next()
.ok_or("input contained no words".to_string())
}
fn main() {
println!("{:?}", first_word("hello world"));
println!("{:?}", first_word(" "));
}This prints Ok("hello") and then Err("input contained no words").
Once the Option has become a Result, you can put ? after it. The usual pattern is option.ok_or(error)?. That line unwraps the value if it is present and returns early with the error if it is not.
ok_or_else: build the error only when needed
The argument to ok_or is evaluated before the call, whether or not the Option is None. If building the error is expensive, you pay for it even on the success path. ok_or_else takes a closure that runs only for None.
fn build_error() -> String {
println!("building the error value");
"value was missing".to_string()
}
fn main() {
let present: Option<i32> = Some(1);
let a: Result<i32, String> = present.ok_or(build_error());
println!("a = {:?}", a);
let b: Result<i32, String> = present.ok_or_else(build_error);
println!("b = {:?}", b);
}The program prints "building the error value" once, for a. The ok_or_else call never runs build_error, because the value is Some.
Use these rules to choose:
- Use
ok_orwhen the error is a cheap constant, such as a unit-like enum variant or an integer code. - Use
ok_or_elsewhen the error allocates (format!,to_string,String::from), copies data, or calls a function. - Use
ok_or_elsewhen the error captures a value from the surrounding scope that you'd have to clone first.
The extra closure costs nothing at runtime in the common case, because the compiler inlines it. When in doubt, choose ok_or_else.
Combining ok_or_else with ? and From
This is the pattern you will use most. The error type has a variant for the missing value and a From impl for the parse failure. One function then uses ? on both an Option and a Result.
use std::num::ParseIntError;
#[derive(Debug)]
enum LineError {
NoSeparator(String),
BadNumber(ParseIntError),
}
impl From<ParseIntError> for LineError {
fn from(e: ParseIntError) -> Self {
LineError::BadNumber(e)
}
}
fn parse_pair(line: &str) -> Result<(String, i32), LineError> {
let (key, value) = line
.split_once('=')
.ok_or_else(|| LineError::NoSeparator(line.to_string()))?;
let n = value.trim().parse::<i32>()?;
Ok((key.trim().to_string(), n))
}
fn main() {
println!("{:?}", parse_pair("retries = 3"));
println!("{:?}", parse_pair("retries"));
println!("{:?}", parse_pair("retries = many"));
}The three calls print an Ok pair, a NoSeparator error, and a BadNumber error. The two ? operators do different work:
- The first
?applies to aResult<_, LineError>thatok_or_elseproduced. The error already has the right type, soFromis the identity conversion. - The second
?applies to aResult<_, ParseIntError>. It callsLineError::fromto convert the error.
ok_or with Box<dyn Error>
When a function returns Result<T, Box<dyn Error>>, you can pass a string slice to ok_or. The standard library implements From<&str> for Box<dyn Error>, so ? converts the string for you.
use std::collections::HashMap;
use std::error::Error;
fn lookup_port(config: &HashMap<String, String>) -> Result<u16, Box<dyn Error>> {
let text = config.get("port").ok_or("missing key: port")?;
let port = text.parse::<u16>()?;
Ok(port)
}
fn main() {
let mut config = HashMap::new();
println!("{:?}", lookup_port(&config).map_err(|e| e.to_string()));
config.insert("port".to_string(), "8080".to_string());
println!("{:?}", lookup_port(&config).map_err(|e| e.to_string()));
}The string is a plain message with no structure. That is fine for a script or a prototype. If callers need to tell the failure cases apart, use an enum as in the previous example.
map_err: change the error you already have
ok_or handles Option to Result. map_err handles Result<T, E> to Result<T, F>. It is how you add context or pick a specific variant when a blanket From impl would be too coarse.
use std::num::ParseIntError;
#[derive(Debug)]
enum FieldError {
Port(ParseIntError),
Timeout(ParseIntError),
}
fn parse_fields(port: &str, timeout: &str) -> Result<(u16, u32), FieldError> {
let port = port.parse::<u16>().map_err(FieldError::Port)?;
let timeout = timeout.parse::<u32>().map_err(FieldError::Timeout)?;
Ok((port, timeout))
}
fn main() {
println!("{:?}", parse_fields("80", "30"));
println!("{:?}", parse_fields("80", "soon"));
}Both fields fail with a ParseIntError, so a single From<ParseIntError> impl could not tell them apart. map_err with a tuple-variant constructor does. A variant name works as a function here, so FieldError::Port is passed directly.
Going the other way: ok() and transpose
To drop the error and keep only success or failure as an Option, call Result::ok. Result::err does the opposite and keeps only the error.
fn parse_or_none(s: &str) -> Option<i32> {
s.trim().parse().ok()
}
fn main() {
println!("{:?}", parse_or_none(" 42 "));
println!("{:?}", parse_or_none("abc"));
}Use ok() only when you truly don't care why the parse failed. It discards the error, and you cannot get it back.
A different mismatch appears with optional values that must be valid when present. You have an Option<&str>, and you want to parse the string if it exists. Mapping gives Option<Result<u32, _>>, which ? cannot unwrap in one step. transpose swaps the layers into Result<Option<u32>, _>.
use std::num::ParseIntError;
fn parse_optional(s: Option<&str>) -> Result<Option<u32>, ParseIntError> {
s.map(|text| text.parse::<u32>()).transpose()
}
fn main() {
println!("{:?}", parse_optional(None));
println!("{:?}", parse_optional(Some("7")));
println!("{:?}", parse_optional(Some("x")));
}The three outcomes stay distinct. Ok(None) means the value was absent, which is allowed. Ok(Some(7)) means it parsed. Err(_) means it was present but invalid. After transpose, ? returns early on the Err and leaves you with a plain Option<u32> to handle.
Gotchas
- Both methods consume the Option.
ok_ortakesselfby value. If you still need the originalOption<String>afterward, callas_ref()oras_deref()first, as inname.as_deref().ok_or(...). - The error type must match what the function returns. After
ok_or, the error type is whatever you passed. If it differs from the function's error type,?needs aFromimpl to bridge them. A missing impl produces a "trait boundFrom<...>is not satisfied" error. - Inference can fail.
None.ok_or("x")alone leaves theOktype unknown. Annotate the binding or the function's return type. - Don't use ok() to "fix" a type mismatch. Converting a
Resultto anOptionjust to use?in anOption-returning function throws away the error. Change the function's return type toResultinstead.
Summary of the methods
| Method | From | To | Evaluates the error |
|---|---|---|---|
| `ok_or(e)` | `Option<T>` | `Result<T, E>` | Always, before the call |
| `ok_or_else(f)` | `Option<T>` | `Result<T, E>` | Only for `None` |
| `ok()` | `Result<T, E>` | `Option<T>` | Drops the error |
| `map_err(f)` | `Result<T, E>` | `Result<T, F>` | Only for `Err` |
| `transpose()` | `Option<Result<T, E>>` | `Result<Option<T>, E>` | Not applicable |
Exercise
The function below should return an error when the slice is empty. Rewrite the body so it uses okorelse and ?, and explain why okorelse is the better choice than ok_or here. fn largest(values: &[i32]) -> Result<i32, String> { // your code }
Show answer
One correct version is:
fn largest(values: &[i32]) -> Result<i32, String> {
let max = values
.iter()
.copied()
.max()
.okorelse(|| format!("no values in slice of length {}", values.len()))?;
Ok(max)
}
max() returns None for an empty iterator. okorelse is better because the error is built with format!, which allocates a String. With okor, that allocation would happen on every call, even when the slice has values and the error is never used. With okor_else, the closure runs only for the empty case.
Exercise
A function has the signature fn getage(map: &HashMap<String, String>, name: &str) -> Result<u8, Box<dyn Error>>. Using one okor call and one ? for the lookup, and a second ? for parsing, write the body. Which two conversions does ? perform?
Show answer
fn getage(map: &HashMap<String, String>, name: &str) -> Result<u8, Box<dyn Error>> {
let text = map.get(name).okor("no such person")?;
let age = text.parse::<u8>()?;
Ok(age)
}
The first ? converts &str into Box<dyn Error> through the standard library's From<&str> impl. The second ? converts ParseIntError into Box<dyn Error>, because ParseIntError implements Error. The function needs use std::collections::HashMap; and use std::error::Error;.