Converting Errors With From And Question Mark

Implement From for each upstream error so one error type owns every failure shape, and let the question mark operator convert automatically at each call site.

RustData Integrity

Code

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

#[derive(Debug)]
enum ConfigError {
    NotANumber(ParseIntError),
    OutOfRange(u32),
}

// 每个上游错误形状各写一个 From:? 处自动转换
impl From<ParseIntError> for ConfigError {
    fn from(e: ParseIntError) -> Self {
        ConfigError::NotANumber(e)
    }
}

fn parse_workers(raw: &str) -> Result<u32, ConfigError> {
    let n: u32 = raw.trim().parse()?; // ParseIntError 经 From 变 ConfigError
    if n == 0 || n > 64 {
        return Err(ConfigError::OutOfRange(n));
    }
    Ok(n)
}

fn main() {
    for raw in ["8", " 16 ", "0", "abc"] {
        match parse_workers(raw) {
            Ok(n) => println!("{raw} -> {n} workers"),
            Err(ConfigError::NotANumber(e)) => println!("{raw} -> not a number: {e}"),
            Err(ConfigError::OutOfRange(n)) => println!("{raw} -> out of range: {n}"),
        }
    }
}

What the code does

Converting Errors With From And Question Mark is built around the functions from, parse_workers and main.

Repetition is confined to for raw in ["8", " 16 ", "0", "abc"] — the rest of the file is straight-line. Nothing throws: the failure path is a Result variant the caller must match. match here is the control flow: arms enumerate the value’s shapes exhaustively.

Watch out for

  • No exceptions hide in this snippet — every failure is a Result value someone must consume.

Applying it

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

The entry point wires parse_workers together — run it once and the whole demo flows.

Statements that matter

return Err(ConfigError::OutOfRange(n));
impl From<ParseIntError> for ConfigError {
fn from(e: ParseIntError) -> Self {
ConfigError::NotANumber(e)
}
}
match parse_workers(raw) {
Ok(n) => println!("{raw} -> {n} workers"),
Err(ConfigError::NotANumber(e)) => println!("{raw} -> not a number: {e}"),
Err(ConfigError::OutOfRange(n)) => println!("{raw} -> out of range: {n}"),
}

Interactive Tools for This Topic

FAQ

How does the code signal failure?
No panics — `Result` values carry the failure, and `?` forwards them to the caller.
How do you run Converting Errors With From And Question Mark?
Direct execution is enough; the script has no external requirements.