Option combinators in Rust
| Map the inside | |
| Chain with and_then | |
| unwrap expect unwrap_or | |
| Early return pattern |
Map the inside
Map transforms the value inside Some and leaves None alone. Give map a closure, and it applies the closure only when a value is present.
The result stays an Option, so absence flows through long chains without extra checks.
fn main() {
let a = Some(3);
let b = a.map(|x| x + 1);
println!("done");
}
Here b becomes Some holding 4. If a were None, map would skip the closure and b would stay None.
Chain with and_then
Use and_then when the next step also returns an Option. The closure runs only for Some, and its result becomes the new value, which flattens two layers into one.
Parsing text is a classic case: convert the string, and a failed parse becomes None automatically.
fn to_num(s: String) -> Option<i32> {
s.parse().ok()
}
fn main() {
let r = Some(String::from("7")).and_then(to_num);
}
The chain starts with text and ends with a number option. Bad input yields None at the parse step with no extra branching.
unwrap expect unwrap_or
Unwrap helpers trade the Option wrapper for a plain value. Prefer unwrap_or with a default so None maps to a safe value instead of stopping the program.
Reserve unwrap and expect for cases that truly cannot fail, since they stop the program on None.
fn main() {
let a: Option<i32> = Some(3);
let x = a.unwrap_or(0);
let y: Option<i32> = None;
let z = y.unwrap_or(0);
}
Here x becomes 3 and z becomes 0. The same call handles both variants, so callers never branch by hand.
Early return pattern
The let else form returns early when the value is absent. It binds the inner value for the rest of the function and handles None in a short else block.
Use this shape at the top of functions to keep the main path flat and free of deep nesting.
fn double_first(v: Vec<i32>) -> i32 {
let Some(x) = v.first().copied() else {
return 0;
};
x * 2
}
Empty input returns 0 at once, while other input flows into the math below. The bound x is a plain number for the rest of the body.
Next: Result and question mark
Article author: Arthur Isaev