Sub topic 2
What the Compiler Does with `?`
Assume you know Rust functions, match, ownership, and basic traits. The ? operator is shorthand for handling a Result or Option and returning early when it contains no usable value.
What `?` Expands To
For a Result, ? keeps the success value. For an error, it returns from the current function.
use std::fs;
use std::io;
fn load_text(path: &str) -> Result<String, io::Error> {
let text = fs::read_to_string(path)?;
Ok(text)
}Conceptually, the operator expands into a match:
let text = match fs::read_to_string(path) {
Ok(value) => value,
Err(error) => return Err(error),
};Converting Errors with `From`
If the expression and function use different error types, ? calls From::from to convert the error.
use std::num::ParseIntError;
fn number(text: &str) -> Result<i32, ParseIntError> {
let value = text.trim().parse::<i32>()?;
Ok(value)
}In a larger function, several error types can convert into one custom error type. Implement From<SourceError> for the destination error. Then ? performs that conversion automatically.
Using `?` with `Option`
With Option, ? returns None for a missing value and unwraps Some:
fn first_upper(text: &str) -> Option<char> {
let first = text.chars().next()?;
Some(first.to_ascii_uppercase())
}Moving Between `Option` and `Result`
Use ok_or or ok_or_else when a missing option should become an error. ok_or_else computes the error only when needed.
fn port(value: Option<&str>) -> Result<u16, String> {
let text = value.ok_or_else(|| "missing port".to_string())?;
text.parse::<u16>().map_err(|e| e.to_string())
}Designing a Custom Error Type
A custom error enum can preserve different failure causes:
use std::{fmt, num::ParseIntError};
#[derive(Debug)]
enum ConfigError {
MissingPort,
InvalidPort(ParseIntError),
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::MissingPort => write!(f, "missing port"),
Self::InvalidPort(e) => write!(f, "invalid port: {e}"),
}
}
}
impl std::error::Error for ConfigError {}
impl From<ParseIntError> for ConfigError {
fn from(error: ParseIntError) -> Self {
Self::InvalidPort(error)
}
}Now a parsing function can use ? on parse, because ParseIntError converts into ConfigError.
Exercise
What must a function return to use ? on a Result?
Show answer
It must return a compatible Result, or another type that can receive the propagated error.