Result Combinators Map Err Unwrap Or Else
Reshape fallible flows with Result combinators: ok_or for Options, map_err to add context, unwrap_or_else and or_else for fallbacks.
Code
fn parse_workers(raw: Option<&str>) -> Result<u32, String> {
// ok_or:None 变成具体错误,Option 升级成 Result
let text = raw.ok_or("workers key missing")?;
let value: u32 = text
.trim()
.parse()
.map_err(|e| format!("workers: {e}"))?; // 换掉底层错误,保留上下文
if value > 64 {
return Err(format!("workers {value} exceeds cap"));
}
Ok(value)
}
fn main() {
println!("{:?}", parse_workers(Some(" 12 ")));
println!("{:?}", parse_workers(None));
println!("{:?}", parse_workers(Some("many")));
// unwrap_or_else:失败时给兜底值;or_else:失败时换一条路径
let capped = parse_workers(Some("5000")).unwrap_or_else(|_| 64);
println!("capped: {}", capped);
let recovered = parse_workers(Some("many"))
.or_else(|_| parse_workers(Some("8")))
.unwrap();
println!("recovered: {}", recovered);
}Inside the snippet
Result Combinators Map Err Unwrap Or Else is built around the functions parse_workers and main.
Fallible operations return Result, and the ? operator short-circuits errors up to the caller.
Caveats
- 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_workers(raw: Option<&str>) -> Result<u32, String>
Output lines are prefixed (capped:, recovered:), making each step’s effect easy to spot.
Treat main as the orchestrator calling parse_workers in a fixed order.
Core lines
let capped = parse_workers(Some("5000")).unwrap_or_else(|_| 64);
return Err(format!("workers {value} exceeds cap"));
let text = raw.ok_or("workers key missing")?;
Interactive Tools for This Topic
FAQ
- How are errors reported?
- Each fallible operation returns `Result`; nothing is silently discarded.
- What does Result Combinators Map Err Unwrap Or Else print when run?
- The script runs standalone; its 2 labeled outputs include `capped:`, `recovered:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.