Sub topic 12
From and the ? operator
This chapter assumes you know Result, match, and how to write impl Trait for Type. It also assumes you have seen From as a conversion trait. Here you will see how ? uses From to convert errors for you.
What ? does on an error
The ? operator unwraps an Ok value. On an Err, it returns early from the function. It does not return the error unchanged, though. It first passes the error through From::from. Roughly, ? expands to this:
match expr {
Ok(value) => value,
Err(e) => return Err(From::from(e)),
}The function's declared error type decides which From implementation runs. If the error already has that type, the conversion does nothing, because the standard library implements From<T> for T. If the types differ, you need an impl From<SourceError> for YourError.
A worked example
Parsing a port number can fail in two ways. The text may not be a number, or the number may not fit in a port. One error enum covers both cases.
use std::fmt;
use std::num::ParseIntError;
#[derive(Debug)]
enum PortError {
Parse(ParseIntError),
OutOfRange(i64),
}
impl fmt::Display for PortError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PortError::Parse(e) => write!(f, "not a number: {}", e),
PortError::OutOfRange(n) => write!(f, "port {} is out of range", n),
}
}
}
impl From<ParseIntError> for PortError {
fn from(e: ParseIntError) -> Self {
PortError::Parse(e)
}
}
fn parse_port(s: &str) -> Result<u16, PortError> {
let n: i64 = s.trim().parse()?;
u16::try_from(n).map_err(|_| PortError::OutOfRange(n))
}
fn main() {
println!("{:?}", parse_port("8080"));
match parse_port("abc") {
Ok(p) => println!("port {}", p),
Err(e) => println!("error: {}", e),
}
if let Err(e) = parse_port("70000") {
println!("error: {}", e);
}
}The output is:
Ok(8080)
error: not a number: invalid digit found in string
error: port 70000 is out of rangeIn parse_port, s.trim().parse()? produces a ParseIntError on failure. The function returns Result<u16, PortError>, so ? calls PortError::from(e). The OutOfRange case is built by hand with map_err, because no standard error type maps to it.
Why this pattern is useful
- The happy path stays free of
matchblocks. - Each failure source needs one
Fromimplementation. Every function that uses?then benefits. - Callers see a single error type. They can
matchon its variants. - Implementing
Displayon the error, as above, gives readable messages for users.
Exercise
Exercise
A function returns Result<u16, PortError>. Inside it, you call "x".parse::<i64>()? and the string is not a number. Which function produces the PortError that is returned, and what must exist for the code to compile?
Show answer
The ? operator calls From::from on the ParseIntError, which runs PortError's implementation of From<ParseIntError> and returns Err(PortError::Parse(e)). The code compiles only if impl From<ParseIntError> for PortError exists.