Result Propagation With Question Mark

Propagate errors up the call stack with the ? operator, converting via From so each layer adds context without match boilerplate.

RustResilience

Code

rustsnippet
37 lines
use std::num::ParseIntError;

#[derive(Debug)]
enum LoadError {
    Parse(ParseIntError),
    Empty,
}

// From 实现让 ? 自动转换底层错误
impl From<ParseIntError> for LoadError {
    fn from(err: ParseIntError) -> Self {
        LoadError::Parse(err)
    }
}

fn parse_port(raw: &str) -> Result<u16, LoadError> {
    if raw.trim().is_empty() {
        return Err(LoadError::Empty);
    }
    // ? 把 ParseIntError 转成 LoadError 并提前返回
    let port: u16 = raw.parse()?;
    Ok(port)
}

fn describe(raw: &str) -> String {
    match parse_port(raw) {
        Ok(port) => format!("port={port}"),
        Err(LoadError::Empty) => String::from("port was empty"),
        Err(LoadError::Parse(err)) => format!("bad port: {err}"),
    }
}

fn main() {
    for raw in ["8080", "", "eighty"] {
        println!("{raw:?} -> {}", describe(raw));
    }
}

Inside the snippet

Structurally, expect the functions from, parse_port, describe and main and nothing else.

Iteration happens inside for raw in ["8080", "", "eighty"] — everything outside it runs once. Fallible operations return Result, and the ? operator short-circuits errors up to the caller. A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.

What to watch for

  • Errors travel through Result; if you drop the ? operators while adapting, each call site needs its own match.

Using it

The main signature reads fn from(err: ParseIntError) -> Self

Execute the file and main walks through describe, in that order.

Key statements

return Err(LoadError::Empty);
impl From<ParseIntError> for LoadError {
    fn from(err: ParseIntError) -> Self {
        LoadError::Parse(err)
    }
}
fn describe(raw: &str) -> String {
    match parse_port(raw) {
        Ok(port) => format!("port={port}"),
        Err(LoadError::Empty) => String::from("port was empty"),
        Err(LoadError::Parse(err)) => format!("bad port: {err}"),
    }
}

Interactive Tools for This Topic

FAQ

What is the error handling style?
Each fallible operation returns `Result`; nothing is silently discarded.
How do you run Result Propagation With Question Mark?
This is a complete program, not a library excerpt — execution starts at the top.