Sub topic 9
Propagating errors with the ? operator
This chapter assumes you can read match on Option and Result, and that you know the basics of generics and traits. You will learn what ? expands to, where it is allowed, and how it converts error types.
What ? does
Without ?, passing an error up to the caller means writing a match at every step. The ? operator does that for you. On Ok(v) it evaluates to v. On Err(e) it returns early from the enclosing function with that error.
use std::num::ParseIntError;
fn sum_two(a: &str, b: &str) -> Result<i32, ParseIntError> {
let x = a.trim().parse::<i32>()?;
let y = b.trim().parse::<i32>()?;
Ok(x + y)
}
fn main() {
println!("{:?}", sum_two("4", " 5 "));
println!("{:?}", sum_two("4", "five"));
}This prints Ok(9) and then Err(ParseIntError { kind: InvalidDigit }). The expression a.trim().parse::<i32>()? behaves roughly like this:
fn expanded(a: &str) -> Result<i32, std::num::ParseIntError> {
let x = match a.trim().parse::<i32>() {
Ok(v) => v,
Err(e) => return Err(From::from(e)),
};
Ok(x)
}
fn main() {
println!("{:?}", expanded("12"));
}The From::from(e) call matters. It lets the error type change on the way out, which the "Error conversion" section covers below.
Using ? with Option
? also works on Option. None returns None from the function.
fn first_char_upper(words: &[&str]) -> Option<char> {
let first = words.first()?;
let c = first.chars().next()?;
Some(c.to_ascii_uppercase())
}
fn main() {
println!("{:?}", first_char_upper(&["rust", "go"]));
println!("{:?}", first_char_upper(&[]));
println!("{:?}", first_char_upper(&[""]));
}The output is Some('R'), None, None.
Error conversion
The error in the ? expression does not have to match the function's error type exactly. It only needs a From implementation from the first type to the second. &str converts to String, so this compiles:
fn port_from(value: Option<&str>) -> Result<u16, String> {
let text = value.ok_or("missing port")?;
let port = text.parse::<u16>().map_err(|e| e.to_string())?;
Ok(port)
}
fn main() {
println!("{:?}", port_from(Some("8080")));
println!("{:?}", port_from(None));
println!("{:?}", port_from(Some("99999")));
}Here ok_or turns the Option into a Result first. map_err converts the parse error to a String by hand. A later chapter replaces map_err with a From implementation on your own error type.
Common errors
?in a function returning(). The compiler reports that?can only be used in a function that returnsResultorOption. Change the return type, or handle the value withmatch.- Mixing
OptionandResult. A function returningResultcannot use?on anOption, and the reverse is also true. Convert withok_ororokfirst. - No
Fromimplementation. If the error types differ and noFromexists, the compiler says the traitFrom<X>is not implemented forY. Add aFromimplementation, or usemap_err.
Exercise
A function has the return type Result<u16, String>. It contains the line let n = "12".parse::<u16>()?;. Why does this fail to compile, and how do you fix it?
Show answer
parse returns Result<u16, ParseIntError>. String has no From<ParseIntError> implementation, so ? cannot convert the error. Fix it with .map_err(|e| e.to_string())?, or change the function's error type to ParseIntError, or to a custom error type that implements From<ParseIntError>.