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
This example demonstrates how to use iterator basic in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.
Key Concepts
- Rust's strong type system catches errors at compile time
- Ownership and borrowing rules ensure memory safety
- Pattern matching makes code expressive and exhaustive
Related Topics
Browse more examples in the iterators category to build a complete understanding of this topic.