Rust Tutorial: Iterators and Closures in Rust
Use iterators, closures, and iterator adapters (map, filter, collect).
Concepts in this chapter
You will learn and practice:
- **Closures** — |x| x * 2, |a, b| a + b
- **Iterator** — .iter(), .into_iter(); .next()
- **map** — transform each element
- **filter** — keep elements matching a predicate
- **collect** — build a Vec or other collection from an iterator
- **Method chains** — iter().map(...).filter(...).collect()
---
Iterator and map
```rust
let nums = vec![1, 2, 3, 4, 5];
let doubled: Vec<i32> = nums.iter().map(|n| n * 2).collect();
for d in &doubled {
println!("{}", d);
}
```
---
filter
```rust
let evens: Vec<_> = nums.iter().filter(|n| *n % 2 == 0).copied().collect();
```
---
What's Next?
You've completed the Rust tutorial track. Try interview prep problems or another language!
What you'll learn in this Rust iterators and closures in rust tutorial
This interactive Rust tutorial has 3 hands-on exercises. Estimated time: 15 minutes.
- Iterator map — Create a vec [1, 2, 3, 4, 5]. Use .iter().map(|n| n * 2).collect::<Vec<_>>() to get doubled values and print each on its…
- Iterator filter — From vec![1, 2, 3, 4, 5], use .iter().filter(|n| *n % 2 == 0).copied().collect::<Vec<_>>() to get evens. Print each on i…
- Sum with iterator — Use .iter().sum::<i32>() on vec![10, 20, 30] to compute the sum and print it.
Rust Iterators and Closures in Rust concepts covered
- Concepts in this chapter
- Iterator and map
- filter
- What's Next?