We can apply and_then
, map_or
, unwrap_or
functions to an Option value:
- and_then: take the wrapped value as parameter if
Some
, return another Option value; or returnNone
ifNone
- map_or: return a fallback value if
None
, and run a mapping function forSome
- map_or_else: run a fallback function if
None
, and a mapping function forSome
- unwrap_or: return a fallback value if
None
, or unwrap the value ifSome
- unwrap_or_else: run a fallback function if
None
, or unwrap the value ifSome
Example
fn main() {
let x = Some(4);
// calculate 2*x + 3
// we can and_then functions
let result = x.and_then(|v| {
Some(v * 2)
}).and_then(|v| {
Some(v + 3)
});
println!("#1: {}", result.unwrap());
// map_or and map_or_else
println!("#2: {}", result.map_or(42, |v| {
v * v
}));
println!("#3: {}", result.map_or_else(
|| {42},
|v| {v * v}
));
// unwrap_or and unwrap_or_else
println!("#4: {}", result.unwrap_or(42));
println!("#5: {}", result.unwrap_or_else(|| {42}));
println!("#6: {}", None.unwrap_or(42));
}
Result:
#1: 11
#2: 121
#3: 121
#4: 11
#5: 11
#6: 42
Top comments (0)