# Should I use for loops or iterator methods like map, filter and collect in Rust?
Source: https://ruststudio.org/community/t/134/should-i-use-for-loops-or-iterator-methods-like-map-filter-and-collect-in-rust
Author: Ruststudio Team (staff) | Published: 2026-12-05 | Updated: 2026-12-05 | Checked with: rustc 1.93.0, Windows 11
Category: Help and questions | Kind: FAQ | Tags: iterators, basics, style | Views: 0

## Short answer
Both are fine and compile to similarly fast code. Use a for loop when the body has side effects or early exits that are easier to read as steps. Use iterator methods such as filter, map, sum and collect when you are transforming a sequence into a value, because they say what you want without a mutable variable.

## Answer
## Answer
An iterator is a value that produces items one at a time. Methods like `filter` and `map` do nothing until something consumes the iterator (`collect`, `sum`, a `for` loop), so a chain is one pass over the data with no temporary lists in between.

```rust title=src/main.rs
fn main() {
    let words = ["apple", "fig", "banana", "kiwi"];

    // loop version
    let mut lengths = Vec::new();
    for w in words {
        if w.len() > 3 {
            lengths.push(w.len());
        }
    }

    // iterator version: same result, no mutable variable
    let lengths2: Vec<usize> = words.iter().filter(|w| w.len() > 3).map(|w| w.len()).collect();

    println!("{lengths:?} {lengths2:?}");
    let total: usize = words.iter().map(|w| w.len()).sum();
    let longest = words.iter().max_by_key(|w| w.len());
    println!("{total} {longest:?}");
    println!("{:?}", words.iter().position(|&w| w == "banana"));
}
```

```text
[5, 6, 4] [5, 6, 4]
18 Some("banana")
Some(2)
```

The answers below show when each style reads better.

## Answers (2)

### Answer 1 by Ruststudio Team (staff), 2026-12-05, 0 votes
## Approach 1: a `for` loop
Use it when each step does something other than produce a value: printing, writing to a file, `break` on a condition, several mutable variables updated together. The first version in the code above is a loop; it is easy to put a `println!` or `break` into.

### Answer 2 by Ruststudio Team (staff), 2026-12-05, 0 votes
## Approach 2: iterator methods
Use them for "take these, keep those, turn each into something, gather the result". `.filter(...).map(...).collect::<Vec<_>>()` states the result directly, and `sum`, `max_by_key`, `position`, `any` and `all` replace whole loops with one word. The type of `collect` decides the result: `Vec<_>`, `HashSet<_>`, `String`, or `Result<Vec<_>, _>` to stop at the first error.

## Common mistakes
- Forgetting that adapters are lazy: `v.iter().map(|x| println!("{x}"));` prints nothing, and the compiler warns that the iterator is unused.
- Collecting into a `Vec` only to loop over it again. Keep chaining instead.
- Writing `.iter()` and getting references. `.iter()` yields `&T`; `.into_iter()` on an owned value yields `T`.
