filter_map and flat_map in Rust
Mapping and filtering in one pass, and flattening nested structure.
fn main() {
let raw = ["3", "x", "7", "", "12"];
let nums: Vec<i32> = raw
.iter()
.filter_map(|s| s.parse().ok())
.collect();
println!("{:?}", nums);
let words = ["hot key", "cold start"];
let parts: Vec<&str> = words
.iter()
.flat_map(|line| line.split(' '))
.collect();
println!("{:?}", parts);
let nested = vec![vec![1, 2], vec![3], vec![]];
println!("{:?}", nested.into_iter().flatten().collect::<Vec<i32>>());
}
How it works
filter_mapkeeps everySomethe closure returns.flat_mapmaps to iterators and concatenates them.flattendoes the same for an iterator of collections.
Keywords and builtins used here
Vecfni32letmainstr
The run, in numbers
- Lines
- 19
- Characters to type
- 419
- Tokens
- 178
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 112 seconds.
Step 4 of 5 in Adapters, step 4 of 14 in Iterators & closures.