Option combinators in Rust
Working inside an Option instead of unwrapping it at every step.
fn main() {
let raw: Option<&str> = Some("42");
let doubled = raw
.and_then(|s| s.parse::<i32>().ok())
.map(|n| n * 2)
.filter(|n| *n > 50);
println!("{:?}", doubled);
let missing: Option<i32> = None;
println!("{}", missing.unwrap_or(0));
println!("{}", missing.unwrap_or_else(|| 7 * 6));
println!("{}", missing.unwrap_or_default());
println!("{:?}", raw.or(Some("fallback")));
}
How it works
maptransforms the value and leavesNonealone.and_thenchains another Option-returning call.unwrap_or_elsesupplies a value only when needed.
Keywords and builtins used here
NoneOptionSomefni32letmainstr
The run, in numbers
- Lines
- 15
- Characters to type
- 381
- Tokens
- 152
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 96 seconds.
Step 2 of 3 in Option, step 2 of 15 in Error handling.