FAQ - Help and questions

Should I use for loops or iterator methods like map, filter and collect in Rust?

#iterators#basics#stylepublished 2 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail
Last post

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.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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.

src/main.rsrust
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.

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    2 answers from the Ruststudio team: different approaches, each with its own trade-offs

    Sort: Oldest Newest
    #2

    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.

      QuoteReply
      Share
      Hacker NewsRedditLinkedInE-mail
      #3

      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.
        QuoteReply
        Share
        Hacker NewsRedditLinkedInE-mail