Skip to content
binshelf/ rust

Search lessons

Type a Rust, TypeScript or C# term, like Option, null or E0382.

    Compare Rust with

    Lessons

    Module 10 · Closures & iterators

    10.2Lazy iterators

    How Rust iterator chains do nothing until a consumer runs them, whether they borrow, change or consume a collection, and how to write your own iterator.

    About 30 minutesIntermediate

    On this page
    1. Concept map
    2. Nothing runs until you ask
    3. Borrow, change or consume
    4. Adapters and consumers
    5. collect builds whatever you ask for
    6. Your own iterator
    7. Which one should I use?
    8. Under the hood
    9. Common pitfalls
    10. Try it yourself

    Concept map

    Concept map: how your language and Rust handle each idea in this lesson
    ConceptTypeScriptC#Rust
    Transform every itemitems.map(f): runs at once and builds a new arrayitems.Select(f): lazy, runs when enumerateditems.iter().map(f): lazy, runs when consumed
    Run the pipelineArray methods run immediately; iterator helpers run on toArray(), reduce(), for…ofToList(), Sum(), First(), foreachA consumer: collect(), sum(), fold(), find(), for
    Run the same pipeline twiceAn iterator is used up; the second pass sees nothingAllowed: each enumeration runs every step againCompile error E0382: the consumer took the iterator
    Read, change or take the itemsNo distinctionNo distinction.iter() (&T), .iter_mut() (&mut T), .into_iter() (T)
    A custom sequenceA generator, function* with yieldIEnumerable<T> with yield returnA struct with impl Iterator: type Item and fn next

    In TypeScriptC#, you transform collections with a chain of calls like scores.filter(...).map(...)scores.Where(...).Select(...). Rust has the same chains, with two differences that matter. First, they’re lazy: building the chain does nothing, and the work happens one item at a time when a consumer such as collect or sum pulls items through it. Second, you choose whether the chain borrows the collection, changes its items, or consumes it. In return, an optimized build turns a chain into code as fast as a hand-written loop.

    Nothing runs until you ask

    Here’s a chain that doubles prices and logs each step, then looks for the first doubled price over 10:

    TypeScript
    prices.ts
    const prices = [3, 8, 12, 5];
    const doubled = prices.values().map((price) => {
      console.log(`doubling ${price}`);
      return price * 2;
    });
    console.log("nothing has run yet");
    const firstBig = doubled.find((price) => price > 10) ?? 0;
    console.log(`first over 10: ${firstBig}`);
    C#
    Prices.cs
    int[] prices = [3, 8, 12, 5];
    var doubled = prices.Select(price =>
    {
        Console.WriteLine($"doubling {price}");
        return price * 2;
    });
    Console.WriteLine("nothing has run yet");
    var firstBig = doubled.FirstOrDefault(price => price > 10);
    Console.WriteLine($"first over 10: {firstBig}");
    Rust
    let prices = [3, 8, 12, 5];
    let mut doubled = prices.iter().map(|price| {
        println!("doubling {price}");
        price * 2
    });
    println!("nothing has run yet");
    let first_big = doubled.find(|price| *price > 10).unwrap_or(0);
    println!("first over 10: {first_big}");

    Output

    nothing has run yet
    doubling 3
    doubling 8
    first over 10: 16

    Building doubled runs no code at all. find then asks for one item at a time: 3 is doubled to 6 (too small), 8 to 16 (a match), and it stops there. 12 and 5 are never touched.

    • prices.iter() creates an iterator that borrows the array, one item at a time.
    • .map(...) is an adapter: it wraps that iterator in a new one and returns immediately.
    • .find(...) is a consumer: it calls next() on the chain until it has an answer.

    doubled is let mut because pulling items out of an iterator advances its position, which changes it. find returns an Option: Some(item) if it found one, None if not. .unwrap_or(0) picks 0 for the “not found” case.

    The TypeScript version uses iterator helpers (ES2025): prices.values() returns an iterator whose map, filter and take are lazy adapters, and whose find, reduce and toArray run them, like Rust’s. The array methods you probably use every day are not. prices.map(...) runs the callback on every item immediately and builds a new array:

    eager.ts
    const prices = [3, 8, 12, 5];
    const doubled = prices.map((price) => {
      console.log(`doubling ${price}`);
      return price * 2;
    });
    console.log("all done already");
    const firstBig = doubled.find((price) => price > 10) ?? 0;
    console.log(`first over 10: ${firstBig}`);

    Output

    doubling 3
    doubling 8
    doubling 12
    doubling 5
    all done already
    first over 10: 16

    Every array method in a chain like filter(...).map(...) builds a whole new array. A Rust chain never does: items flow through one at a time.

    This is the behavior you know from LINQ: Select and Where are deferred, and FirstOrDefault runs the pipeline only until it finds a match. Rust’s iterators are the same idea. The differences are in who may run a pipeline twice (see Common pitfalls) and in what the compiled code looks like (see Under the hood).

    If no consumer ever runs, nothing happens at all, even side effects you meant to run:

    let prices = [3, 8, 12, 5];
    let doubled = prices.iter().map(|price| {
        println!("doubling {price}");
        price * 2
    });
    println!("built a pipeline, never ran it");

    Output

    built a pipeline, never ran it

    If you call .map(...) without storing the result at all, the compiler warns: “unused Map that must be used”, with the note “iterators are lazy and do nothing unless consumed”.

    Borrow, change or consume

    The first call in a chain decides what each item is and what happens to the collection. It’s the same choice as for x in &v, &mut v and v in Loops & conditional expressions, spelled as methods:

    let mut prices = vec![3, 8, 12];
    
    let total: i32 = prices.iter().sum(); // items are &i32; prices is only read
    
    for price in prices.iter_mut() {
        *price *= 2; // items are &mut i32; prices changes in place
    }
    
    let labels: Vec<String> = prices
        .into_iter() // items are i32; prices is moved into the iterator
        .map(|price| format!("${price}"))
        .collect();
    
    println!("{total} {labels:?}");

    Output

    23 ["$6", "$16", "$24"]
    MethodEach item isThe collection afterwards
    .iter()&T, a shared borrowUnchanged and still yours
    .iter_mut()&mut T, a mutable borrowChanged in place, still yours
    .into_iter()T, the value itselfGone: moved into the iterator

    TypeScriptC# has no such choice, because every collection is shared by reference. In Rust, .into_iter() is what lets you move the Strings out of a Vec<String> without cloning them, and .iter() is what lets you keep the Vec afterwards.

    An iterator from .iter() is a borrow of the collection, and it holds that borrow until its last use. So you can’t change the collection while an iterator over it is still going to be used:

    let mut scores = vec![72, 45, 91];
    let mut iter = scores.iter();
    scores.push(60);
    println!("{:?}", iter.next());

    Rust doesn't compile this: error E0502

    error[E0502]: cannot borrow `scores` as mutable because it is also borrowed as immutable
     --> main.rs:3:1
      |
    2 | let mut iter = scores.iter();
      |                ------ immutable borrow occurs here
    3 | scores.push(60);
      | ^^^^^^^^^^^^^^^ mutable borrow occurs here
    4 | println!("{:?}", iter.next());
      |                  ---- immutable borrow later used here
    An iterator borrows its collection
    An iterator borrows its collection. Each column is a value or a borrow; a mark means it's alive on that line.
    LineCodescoresowneriter (&scores)shared borrow (&)&mut scoresmutable borrow (&mut)What happens
    1let mut scores = vec![72, 45, 91];ownsscores starts
    2let mut iter = scores.iter();scores alive&iter (&scores) startsiter borrows scores
    3scores.push(60);scores aliveiter (&scores) alive&mut&mut scores startserrorE0502: push needs &mut scores, but iter is still alive
    4println!("{:?}", iter.next());scores endsiter (&scores) endsLast use of iter: the borrow ends here

    A timeline of the four lines above. scores owns the vector from line 1 to line 4. iter, created by scores.iter(), is a shared borrow of scores from line 2 until its last use on line 4. push needs a mutable borrow of scores on line 3 while iter is still alive, so the compiler rejects line 3 with E0502.

    In TypeScript, an iterator over an array keeps going over whatever the array holds when it asks for the next item, so a push during iteration silently changes what you see.In C#, this is the “Collection was modified; enumeration operation may not execute” exception, thrown on the next MoveNext(). In Rust, it’s a compile error. push might move the vector to a bigger buffer, and the iterator would be left pointing at freed memory.

    Adapters and consumers

    A chain is a source (.iter() and friends), any number of adapters, and one consumer at the end. Here’s a typical one: the first two passing players, and how many passed.

    TypeScript
    players.ts
    const players: [string, number][] = [
      ["Ada", 72],
      ["Bo", 45],
      ["Cy", 91],
      ["Di", 60],
      ["Ed", 38],
    ];
    
    const firstPassing = players
      .values()
      .filter(([, score]) => score >= 50)
      .map(([name, score]) => `${name} (${score})`)
      .take(2)
      .toArray();
    console.log(firstPassing.join(", "));
    
    const total = players.values().reduce((sum, [, score]) => sum + score, 0);
    const passed = players.values().filter(([, score]) => score >= 50).toArray().length;
    console.log(`total ${total}, ${passed} passed`);
    C#
    Players.cs
    (string Name, int Score)[] players = [("Ada", 72), ("Bo", 45), ("Cy", 91), ("Di", 60), ("Ed", 38)];
    
    var firstPassing = players
        .Where(player => player.Score >= 50)
        .Select(player => $"{player.Name} ({player.Score})")
        .Take(2)
        .ToList();
    Console.WriteLine(string.Join(", ", firstPassing));
    
    var total = players.Sum(player => player.Score);
    var passed = players.Count(player => player.Score >= 50);
    Console.WriteLine($"total {total}, {passed} passed");
    Rust
    let players = [("Ada", 72), ("Bo", 45), ("Cy", 91), ("Di", 60), ("Ed", 38)];
    
    let first_passing: Vec<String> = players
        .iter()
        .filter(|(_, score)| *score >= 50)
        .map(|(name, score)| format!("{name} ({score})"))
        .take(2)
        .collect();
    println!("{}", first_passing.join(", "));
    
    let total: i32 = players.iter().map(|(_, score)| score).sum();
    let passed = players.iter().filter(|(_, score)| *score >= 50).count();
    println!("total {total}, {passed} passed");

    Output

    Ada (72), Cy (91)
    total 306, 3 passed

    take(2) stops the whole chain after two items, so Di and Ed are never filtered or formatted. The closures take each tuple apart in their parameter list, |(name, score)|, the same destructuring as in match & destructuring.

    Here are the adapters and consumers you’ll use most, with their TypeScriptC# names:

    RustWhat it doesTypeScript (iterator helper or array method)
    map(f)Transforms each itemmap(f)
    filter(f)Keeps items where f returns truefilter(f)
    flat_map(f)Turns each item into several and flattens themflatMap(f)
    take(n) / skip(n)The first n items / all but the first ntake(n) / drop(n)
    enumerate()Pairs each item with its positionArrays: entries(). Iterators: none
    zip(other)Pairs items from two iteratorsNone built in
    rev()Walks backwardsArrays: toReversed() (eager). Iterators: none
    collect()Builds a collection: Vec, String, HashMap, …toArray(), new Map(...), new Set(...)
    sum() / count()Adds up / counts the itemsreduce((a, b) => a + b, 0) / none
    fold(init, f)Combines all items into one valuereduce(f, init)
    find(f)The first match, as an Optionfind(f), undefined if none
    any(f) / all(f)Does any / every item match?some(f) / every(f)
    for_each(f)Runs f on each itemforEach(f)
    RustWhat it doesLINQ
    map(f)Transforms each itemSelect(f)
    filter(f)Keeps items where f returns trueWhere(f)
    flat_map(f)Turns each item into several and flattens themSelectMany(f)
    take(n) / skip(n)The first n items / all but the first nTake(n) / Skip(n)
    enumerate()Pairs each item with its positionIndex() (.NET 9+) or Select((x, i) => ...)
    zip(other)Pairs items from two sequencesZip(other)
    rev()Walks backwardsReverse(). On a List<T>, list.Reverse() is the list’s own method: it reverses in place and returns nothing. Write list.AsEnumerable().Reverse()
    collect()Builds a collection: Vec, String, HashMap, …ToList(), ToArray(), ToDictionary(), ToHashSet()
    sum() / count()Adds up / counts the itemsSum() / Count()
    fold(init, f)Combines all items into one valueAggregate(init, f)
    find(f)The first match, as an OptionFirstOrDefault(f)
    any(f) / all(f)Does any / every item match?Any(f) / All(f)
    for_each(f)Runs f on each itemA foreach loop

    A few more in action:

    let names = ["Ada", "Grace", "Linus"];
    let scores = [72, 91, 60];
    
    for (rank, name) in names.iter().enumerate() {
        println!("{}. {name}", rank + 1);
    }
    
    let pairs: Vec<String> = names
        .iter()
        .zip(scores.iter())
        .map(|(name, score)| format!("{name}={score}"))
        .collect();
    println!("{}", pairs.join(" "));
    
    let backwards: Vec<&str> = names.iter().rev().copied().collect();
    println!("{backwards:?}");
    
    let initials: String = names.iter().flat_map(|name| name.chars().take(2)).collect();
    println!("{initials}");
    
    let longest = names
        .iter()
        .fold(0, |longest, name| longest.max(name.len()));
    println!("{longest}");

    Output

    1. Ada
    2. Grace
    3. Linus
    Ada=72 Grace=91 Linus=60
    ["Linus", "Grace", "Ada"]
    AdGrLi
    5

    .copied() turns the &&str items from .iter() into plain &str values; use .cloned() for types that aren’t Copy, like String.

    collect builds whatever you ask for

    collect can build a Vec, a String, a HashMap, a HashSet and more. It can’t guess which, so you say so, either on the variable or on the call:

    TypeScript
    words.ts
    const words = ["apple", "kiwi", "banana"];
    const upper = words.values().map((word) => word.toUpperCase()).toArray();
    const initials = words.values().map((word) => word.slice(0, 1)).toArray().join("");
    const lengths = new Map(words.values().map((word): [string, number] => [word, word.length]));
    console.log(upper.join(" "));
    console.log(initials);
    console.log(lengths.get("banana"));
    C#
    Words.cs
    string[] words = ["apple", "kiwi", "banana"];
    var upper = words.Select(word => word.ToUpperInvariant()).ToList();
    var initials = string.Concat(words.Select(word => word[..1]));
    var lengths = words.ToDictionary(word => word, word => word.Length);
    Console.WriteLine(string.Join(" ", upper));
    Console.WriteLine(initials);
    Console.WriteLine(lengths["banana"]);
    Rust
    use std::collections::HashMap;
    
    fn main() {
        let words = ["apple", "kiwi", "banana"];
        let upper: Vec<String> = words.iter().map(|word| word.to_uppercase()).collect();
        let initials = words.iter().map(|word| &word[..1]).collect::<String>();
        let lengths: HashMap<&str, usize> = words.iter().map(|word| (*word, word.len())).collect();
        println!("{}", upper.join(" "));
        println!("{initials}");
        println!("{}", lengths["banana"]);
    }

    Output

    APPLE KIWI BANANA
    akb
    6
    • On the variable: let upper: Vec<String> = ... .collect();
    • On the call: .collect::<String>(). The ::<...> is called the turbofish: it passes a type argument to a generic method, where TypeScriptC# would write method<string>()Method<string>(). Rust needs the :: there so the < isn’t read as “less than”.
    • Only the part you care about: Vec<_> asks for a Vec and lets the compiler fill in the item type.

    A HashMap collects from (key, value) pairs. Collecting text pieces (&str or char) into a String concatenates them. And collecting Results into a Result<Vec<_>, _> stops at the first error, which Result and ? builds on:

    let parsed: Result<Vec<i32>, _> = ["1", "2", "x"]
        .iter()
        .map(|text| text.parse::<i32>())
        .collect();
    println!("{}", parsed.is_err());

    Output

    true

    Your own iterator

    Any type can be an iterator: implement the Iterator trait, which needs one type and one method. Here’s an endless Fibonacci sequence:

    TypeScript
    fibonacci.ts
    function* fibonacci(): Generator<number> {
      let current = 0;
      let upcoming = 1;
      while (true) {
        yield current;
        [current, upcoming] = [upcoming, current + upcoming];
      }
    }
    
    const first = fibonacci().take(10).toArray();
    console.log(`[${first.join(", ")}]`);
    const evenSum = fibonacci()
      .filter((n) => n % 2 === 0)
      .take(5)
      .reduce((sum, n) => sum + n, 0);
    console.log(evenSum);
    C#
    Fibonacci.cs
    var first = Fibonacci().Take(10).ToList();
    Console.WriteLine($"[{string.Join(", ", first)}]");
    var evenSum = Fibonacci().Where(n => n % 2 == 0).Take(5).Sum();
    Console.WriteLine(evenSum);
    
    static IEnumerable<long> Fibonacci()
    {
        long current = 0;
        long upcoming = 1;
        while (true)
        {
            yield return current;
            (current, upcoming) = (upcoming, current + upcoming);
        }
    }
    Rust
    struct Fibonacci {
        current: u64,
        upcoming: u64,
    }
    
    impl Iterator for Fibonacci {
        type Item = u64;
    
        fn next(&mut self) -> Option<u64> {
            let value = self.current;
            self.current = self.upcoming;
            self.upcoming += value;
            Some(value)
        }
    }
    
    fn fibonacci() -> Fibonacci {
        Fibonacci {
            current: 0,
            upcoming: 1,
        }
    }
    
    fn main() {
        let first: Vec<u64> = fibonacci().take(10).collect();
        println!("{first:?}");
        let even_sum: u64 = fibonacci().filter(|n| n % 2 == 0).take(5).sum();
        println!("{even_sum}");
    }

    Output

    [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
    188
    • type Item = u64; names what the iterator produces. It’s an associated type: like a generic parameter, but each implementation picks exactly one.
    • fn next(&mut self) -> Option<u64> returns Some(item) for the next item, or None when the sequence is over. This one never ends, so it never returns None; take is what stops it.
    • Everything else comes free. map, filter, take, sum and the rest are default methods on Iterator (default methods are covered in Traits), so they work on Fibonacci the moment it has next. A for loop works too: for n in fibonacci().take(3).

    Rust has no stable yield yet, so where TypeScriptC# lets you write a generatoran iterator method with yield return and turns it into a state machine for you, in Rust you write that state machine yourself: a struct holding the state, and next advancing it. For a quick one-off, std::iter::from_fn(|| ...) turns a closure into an iterator without a struct.

    Which one should I use?

    WhatWhenWhyHow
    .iter()You only read the items. The default.Borrows: nothing is copied, and the collection is still yours afterwards.scores.iter().sum::<i32>(). Items are &T.
    .iter_mut()You change items in place.Borrows mutably: no index, no bounds checks, no new collection.for score in scores.iter_mut() { *score += 5; }
    .into_iter()You’re done with the collection, or you need owned items to move somewhere else.Hands out the values themselves, so Strings and other owned items move without a clone.names.into_iter().map(...). The collection can’t be used afterwards.
    An iterator chainYou compute something from a collection: a new collection, a sum, a count, a found item.Says what, not how. No index variables, no intermediate collections, and it compiles to a loop.scores.iter().filter(...).map(...).collect::<Vec<_>>()
    A for loopThe point is a side effect per item (printing, writing, sending), or you need break, continue, return or ? in the middle.Control flow reads naturally, and side effects don’t hide inside a map.for player in &players { ... }
    collect()You need the result as a collection: to keep it, index it, or loop over it twice.Builds exactly the type you name.let names: Vec<_> = ... .collect(); Don’t collect just to call .len() or loop once: use count() or consume the iterator directly.
    impl IteratorYou write the logic for a sequence: its own type with next.Every adapter and consumer works on it immediately.impl Iterator for Fibonacci { type Item = u64; fn next(&mut self) -> Option<u64> { ... } }

    Rule of thumb: start chains with .iter(), and switch to .iter_mut() to change items or .into_iter() when you’re finished with the collection. Use a chain when you’re computing a value and a for loop when you’re doing something per item. Collect only at the end, and only when you need a collection.

    Loop or iterator chain?
    1. Is the point a side effect per item: printing, writing to a file, sending a message?

      Yes

      Use a for loopfor_each works too, but a loop reads better and allows break and continue.

      No
    2. Do you need return, ? or break in the middle, or update several variables per item?

      Yes

      Use a for loopEarly exits and several pieces of state are clearer as plain statements.

      No
    3. Otherwise: Use an iterator chain: you're turning a collection into a value (a sum, a count, a match) or into another collection. Start it with .iter().

    Under the hood

    Each adapter is a small struct that wraps the iterator before it. players.iter().filter(...).map(...) is a Map that holds a Filter that holds a slice iterator, plus the two closures. When the consumer calls next() on the Map, it calls next() on the Filter, which calls next() on the slice iterator until an item passes. No list is built between the steps, and the whole chain lives on the stack:

    let scores = [72, 45, 91, 60];
    let pipeline = scores
        .iter()
        .filter(|score| **score >= 50)
        .map(|score| score * 2);
    println!("{} bytes", size_of_val(&pipeline));

    Output

    16 bytes

    Today, on a 64-bit target, that’s 16 bytes: the slice iterator’s two pointers (where it is and where it ends). The closures capture nothing, so they take no space.

    Because every type in the chain is known at compile time, including each closure’s, the compiler generates code specialized for this exact chain and inlines all the next() calls into one loop. In an optimized (release) build, these two functions compile to essentially the same machine code, down to the same vectorized loop:

    fn even_squares_loop(numbers: &[i32]) -> i32 {
        let mut total = 0;
        for n in numbers {
            if n % 2 == 0 {
                total += n * n;
            }
        }
        total
    }
    
    fn even_squares_chain(numbers: &[i32]) -> i32 {
        numbers.iter().filter(|n| *n % 2 == 0).map(|n| n * n).sum()
    }
    
    fn main() {
        let numbers = [1, 2, 3, 4];
        let by_loop = even_squares_loop(&numbers);
        let by_chain = even_squares_chain(&numbers);
        println!("{by_loop} {by_chain}");
    }

    Output

    20 20

    This is what Rust calls a zero-cost abstraction: the chain costs nothing over the loop you’d write by hand. Iterating a slice also needs no bounds checks, while numbers[i] checks the index on every access unless the optimizer can prove it’s in range. The inlining happens only with optimizations on: in a debug build, a chain is noticeably slower than a loop, so measure speed with cargo run --release.

    In TypeScript, each array method allocates a new array for its result, so a three-step chain builds two arrays you throw away. Iterator helpers avoid those arrays, but each step still goes through the iterator protocol at run time, calling next() and creating a { value, done } result, unless the engine manages to optimize it away.

    In C#, each LINQ operator allocates an enumerator object, and every item goes through interface calls (MoveNext, Current) and a delegate call for each step. The runtime special-cases some combinations, but in general a LINQ chain costs more than the equivalent foreach. A Rust chain doesn’t.

    Common pitfalls

    Common pitfallfilter hands you a reference to a reference

    .iter() produces &i32 items, and filter lends each item to your closure by reference so it can pass the item on afterwards. So the closure gets a &&i32, and comparing it with a number doesn’t compile:

    let scores = vec![72, 45, 91];
    let passing: Vec<&i32> = scores.iter().filter(|score| score >= 50).collect();

    Rust doesn't compile this: error E0308

    error[E0308]: mismatched types
     --> main.rs:2:64
      |
    2 | let passing: Vec<&i32> = scores.iter().filter(|score| score >= 50).collect();
      |                                                                ^^ expected `&&_`, found integer
      |
      = note: expected reference `&&_`
                      found type `{integer}`

    Dereference twice (**score >= 50), take the item apart in the pattern (|&&score| score >= 50), or call .copied() before filter so the items are plain i32 (|score| *score >= 50). map doesn’t have this problem: it takes each item by value, so its closure gets a &i32.

    Common pitfallAn iterator runs once

    Consumers like sum, count and collect take the iterator by value, so you can’t use it again afterwards:

    let scores = vec![72, 45, 91];
    let doubled = scores.iter().map(|score| score * 2);
    let total: i32 = doubled.sum();
    println!("{total}");
    let count = doubled.count();

    Rust doesn't compile this: error E0382

    error[E0382]: use of moved value: `doubled`
     --> main.rs:5:13
      |
    2 | let doubled = scores.iter().map(|score| score * 2);
      |     ------- move occurs because `doubled` has type `Map<std::slice::Iter<'_, i32>, {closure@main.rs:2:33: 2:40}>`, which does not implement the `Copy` trait
    3 | let total: i32 = doubled.sum();
      |                          ----- `doubled` moved due to this method call
    4 | println!("{total}");
    5 | let count = doubled.count();
      |             ^^^^^^^ value used here after move
      |
    note: `std::iter::Iterator::sum` takes ownership of the receiver `self`, which moves `doubled`
    help: you can `clone` the value and consume it, but this might not be your desired behavior
      |
    3 | let total: i32 = doubled.clone().sum();
      |                         ++++++++

    In TypeScript, a used-up iterator gives you nothing the second time, silently: a second toArray() returns [].In C#, enumerating a LINQ query twice runs it twice, silently: every Select lambda runs again, and a query against a database hits it again. Rust makes the choice explicit. Call scores.iter() again to build a fresh iterator (it’s cheap: nothing was copied), or collect once into a Vec and reuse that.

    Common pitfallmap for side effects does nothing

    names.iter().map(|name| println!("{name}")); prints nothing: there’s no consumer. The compiler warns (“iterators are lazy and do nothing unless consumed”), but it’s easy to miss. For side effects, write a for loop, or .for_each(...) at the end of a chain.

    Common pitfallcollect and sum need a type

    collect can build many collection types and sum can produce many number types, so a bare let total = scores.iter().sum(); is an error (E0283, “type annotations needed”). Name the type on the variable, let total: i32 = ..., or with the turbofish, .sum::<i32>().

    Try it yourself

    Exercise: port this to Rust

    Port this to Rust with two iterator chains: the long words in upper case, and the total number of letters.

    Starting code in TypeScript
    word-stats.ts
    const words = ["iterators", "are", "lazy", "until", "consumed"];
    const long = words
      .values()
      .filter((word) => word.length > 4)
      .map((word) => word.toUpperCase())
      .toArray();
    console.log(long.join(" "));
    const letters = words.values().reduce((total, word) => total + word.length, 0);
    console.log(`${letters} letters`);
    Starting code in C#
    WordStats.cs
    string[] words = ["iterators", "are", "lazy", "until", "consumed"];
    var longWords = words
        .Where(word => word.Length > 4)
        .Select(word => word.ToUpperInvariant())
        .ToList();
    Console.WriteLine(string.Join(" ", longWords));
    var letters = words.Sum(word => word.Length);
    Console.WriteLine($"{letters} letters");

    Expected output

    ITERATORS UNTIL CONSUMED
    29 letters
    Show a hint

    Start both chains with words.iter(). The first is filter, map and collect into a Vec<String>; the second maps each word to its length and sums it into a usize.

    Show a solution
    let words = ["iterators", "are", "lazy", "until", "consumed"];
    let long: Vec<String> = words
        .iter()
        .filter(|word| word.len() > 4)
        .map(|word| word.to_uppercase())
        .collect();
    println!("{}", long.join(" "));
    let letters: usize = words.iter().map(|word| word.len()).sum();
    println!("{letters} letters");

    words.iter() borrows the array, so it can be used for both chains. filter gets a reference to each item, but word.len() works through references, so no dereference is needed. collect needs the Vec<String> annotation and sum needs usize, because both can build more than one type.

    Saved in this browser only.