map and filter
- Rust course
- Intermediate
- Lesson 50/115
- 4 min
Transform iterators with the map and filter adaptors.
map and filter
map and filter are adapters returning a new iterator. They are chained to build data-processing pipelines:
let sonuc: Vec<i32> = (1..=10)
.filter(|n| n % 3 == 0) // 3, 6, 9
.map(|n| n * n) // 9, 36, 81
.collect();map transforms each element, filter drops those failing the condition. filter_map does both: if the closure returns Some(x) it keeps it, if None it drops it.
Other adapters
Other commonly used adapters:
(1..=5).take(2) // 1, 2
(1..=5).skip(3) // 4, 5
(1..=5).rev() // 5, 4, 3, 2, 1
(1..=5).step_by(2) // 1, 3, 5
(1..=3).chain(7..=8) // 1, 2, 3, 7, 8
(1..=10).take_while(|n| n * n < 20) // 1, 2, 3, 4Adapters only return iterators; to get a result, the chain must end with a consuming method (collect, sum, for).
Practice Squares of multiples of three
In the range 1..=10, select the multiples of 3 with filter, square them with map, collect into a vector and print it.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn main() {
let sonuc: Vec<i32> = (1..=10).filter(|n| n % 3 == 0).map(|n| n * n).collect();
println!("{:?}", sonuc);
}Expected output
[9, 36, 81]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is <code>["1", "a", "3"].iter().filter_map(|s| s.parse::<i32>().ok()).sum::<i32>()</code>?
- 0
- 4 Correct answer
- Panic
- 13
Explanation: "a" can't be parsed, becomes None and is dropped; 1 + 3 = 4.
2 Transform
let kareler: Vec<i32> = (1..=3).____(|n| n * n).collect();
let kareler: Vec<i32> = (1..=3).map(|n| n * n).collect();
Explanation: map replaces each element with the closure's result.
3 Chain and result
| Term | Meaning |
|---|---|
(1..=5).take(2) |
1, 2 |
(1..=5).skip(3) |
4, 5 |
(1..=5).step_by(2) |
1, 3, 5 |
(1..=3).chain(7..=8) |
1, 2, 3, 7, 8 |