intermediateIterators
Iterator Basic
Use iterator adaptors: map, filter, collect.
Iterator Basic
Use iterator adaptors: map, filter, collect.
Difficulty
Intermediate
Code
rust
fn main() {
let nums = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let evens: Vec<i32> = nums.iter()
.filter(|&&x| x % 2 == 0)
.copied()
.collect();
println!("evens: {:?}", evens);
let doubled: Vec<i32> = nums.iter().map(|&x| x * 2).collect();
println!("doubled: {:?}", doubled);
}Explanation
Iterators are lazy. Adaptors like map/filter are only evaluated when consumed.
Key Concepts
- Read the code carefully and understand the data flow
- Try modifying the example to see how it changes behavior
- Run this code in the Rust Playground
Related Topics
Browse more examples in the iterators category to build a complete understanding of this topic.