Option in Rust
Representing a value that may be absent.
fn find_even(items: &[i32]) -> Option<i32> {
items.iter().copied().find(|n| n % 2 == 0)
}
fn main() {
let nums = [1, 3, 4, 7];
let even = find_even(&nums);
let doubled = even.map(|n| n * 2).unwrap_or(0);
if let Some(v) = even {
println!("found {v}");
}
println!("{doubled}");
}
How it works
findreturnsOption<i32>, maybe nothing.mapandunwrap_ortransform or default it.if let Some(v)unwraps when present.
Keywords and builtins used here
OptionSomefind_evenfni32ifletmain
The run, in numbers
- Lines
- 14
- Characters to type
- 279
- Tokens
- 111
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 70 seconds.
Step 1 of 3 in Option, step 1 of 15 in Error handling.