Chain Fallible Steps With Result And Then
and_then chains parse, validate, and transform steps so the first Err short-circuits the pipeline while Ok values flow into the next fallible function.
Code
use std::num::ParseIntError;
// 三个独立失败点串成流水线:错误类型统一成 String,and_then 才能直接接续
fn parse(raw: &str) -> Result<i32, String> {
raw.trim().parse::<i32>().map_err(|err: ParseIntError| err.to_string())
}
fn validate(value: i32) -> Result<i32, String> {
if (1..=100).contains(&value) {
Ok(value)
} else {
Err(format!("out of range: {value}"))
}
}
fn double(value: i32) -> Result<i32, String> {
Ok(value * 2)
}
fn main() {
// and_then 只在上一步 Ok 时进入下一步:首个 Err 直接短路成最终结果
let pipeline = |raw: &str| parse(raw).and_then(validate).and_then(double);
for raw in ["21", " 7 ", "150", "abc"] {
match pipeline(raw) {
Ok(doubled) => println!("{raw:?} -> {doubled}"),
Err(err) => println!("{raw:?} -> error: {err}"),
}
}
}How it works
Chain Fallible Steps With Result And Then reduces to the functions parse, validate, double and main.
Repetition is confined to for raw in ["21", " 7 ", "150", "abc"] — the rest of the file is straight-line. Fallible operations return Result, forcing the caller to handle both arms explicitly. Each possible shape of the input gets its own match arm, and the compiler checks the set is complete.
What to watch for
- Errors travel through
Result; if you drop the?operators while adapting, each call site needs its ownmatch.
Putting it to use
The primary signature is fn parse(raw: &str) -> Result<i32, String>
There are 1 call inside main — parse — executed top to bottom.
Core lines
fn validate(value: i32) -> Result<i32, String> {
if (1..=100).contains(&value) {
Ok(value)
} else {
Err(format!("out of range: {value}"))
}
}
fn double(value: i32) -> Result<i32, String> {
Ok(value * 2)
}
fn parse(raw: &str) -> Result<i32, String> {
raw.trim().parse::<i32>().map_err(|err: ParseIntError| err.to_string())
}
Interactive Tools for This Topic
FAQ
- What is the error handling style?
- Through the type system: failures are `Result` variants the caller must consume.
- How do you run Chain Fallible Steps With Result And Then?
- The runtime alone is enough: execute the file as a complete program.
Report a problem with this exampleOpens a pre-filled issue on GitHub.