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.
Code
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 ownmatch.
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
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.