Sub topic 1
Result and the ? operator: a quick refresher
Prerequisites
This chapter assumes you know basic Rust syntax, enums, and pattern matching. It also assumes you have used Option and Result, know what a trait and a derive attribute are, and can add a dependency with Cargo. The chapter reviews how Result and ? work, because the rest of the tutorial builds on one detail: ? converts error types.
Result in one minute
Result<T, E> is an enum with two variants. Ok(T) holds a success value and Err(E) holds an error value. Fallible standard library functions return it, so the compiler makes you handle the failure case.
use std::num::ParseIntError;
fn parse_port(s: &str) -> Result<u16, ParseIntError> {
match s.trim().parse::<u16>() {
Ok(port) => Ok(port),
Err(e) => Err(e),
}
}
fn main() {
println!("{:?}", parse_port(" 8080 "));
println!("{:?}", parse_port("abc"));
}This prints Ok(8080) and then Err(ParseIntError { kind: InvalidDigit }). The match only passes the result along, which is the most common pattern in Rust code. The ? operator exists to shorten it.
What ? does
Placed after an expression of type Result, ? does one of two things:
- If the value is
Ok(v), the expression evaluates tov. - If the value is
Err(e), the function returns early withErrholdinge, converted as described in the next section.
Here is parse_port rewritten with ?:
use std::num::ParseIntError;
fn parse_port(s: &str) -> Result<u16, ParseIntError> {
let port = s.trim().parse::<u16>()?;
Ok(port)
}
fn main() {
println!("{:?}", parse_port("443"));
}You can use ? only in a function whose return type can hold the failure. That means Result, Option, or another type that supports it. Using ? in a function that returns () is a compile error. Rust 2021 main may return Result<(), E>, which later chapters use.
The hidden conversion
? does more than return the error. It calls From::from on the error first. The expression expr? behaves roughly like this:
// Roughly what `expr?` expands to
match expr {
Ok(value) => value,
Err(e) => return Err(From::from(e)),
}So ? compiles whenever the function's error type F implements From<E> for the error type E you are propagating. Every type implements From<Self>, so the same-type case needs no extra work.
Conversion lets one function propagate several kinds of failure. The standard library supplies a conversion from any error type into Box<dyn std::error::Error>:
use std::error::Error;
use std::fs;
fn read_port(path: &str) -> Result<u16, Box<dyn Error>> {
let text = fs::read_to_string(path)?; // io::Error becomes Box<dyn Error>
let port = text.trim().parse::<u16>()?; // ParseIntError becomes Box<dyn Error>
Ok(port)
}
fn main() {
match read_port("port.txt") {
Ok(port) => println!("port {port}"),
Err(e) => eprintln!("error: {e}"),
}
}This works, but the caller gets an opaque box. It cannot tell an I/O failure from a parse failure without extra effort. A precise error type fixes that, and defining one is the subject of the next chapters.
A common error
Suppose a function returns Result<u16, ParseIntError> but also reads a file. The ? on read_to_string fails to compile:
use std::fs;
use std::num::ParseIntError;
fn read_port(path: &str) -> Result<u16, ParseIntError> {
let text = fs::read_to_string(path)?;
text.trim().parse::<u16>()
}The compiler reports that ? cannot convert std::io::Error to ParseIntError, because ParseIntError has no From<std::io::Error> implementation. The fix is a return type that can represent both failures. This gap is why custom error types exist.
What comes next
The next chapters ask what a type needs in order to count as an error. After that you write one by hand, so you can see the From conversion that ? relies on.
Exercise
A function returns Result<u16, MyError>. It contains the line let n = s.parse::<u16>()?;. What must be true for this line to compile?
Show answer
MyError must implement From<std::num::ParseIntError>. The ? operator calls From::from on the ParseIntError before returning Err, so without that implementation the compiler reports a conversion error.