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.
On this page
Concept map
| Concept | TypeScript | C# | Rust |
|---|---|---|---|
| Transform every item | items.map(f): runs at once and builds a new array | items.Select(f): lazy, runs when enumerated | items.iter().map(f): lazy, runs when consumed |
| Run the pipeline | Array methods run immediately; iterator helpers run on toArray(), reduce(), for…of | ToList(), Sum(), First(), foreach | A consumer: collect(), sum(), fold(), find(), for |
| Run the same pipeline twice | An iterator is used up; the second pass sees nothing | Allowed: each enumeration runs every step again | Compile error E0382: the consumer took the iterator |
| Read, change or take the items | No distinction | No distinction | .iter() (&T), .iter_mut() (&mut T), .into_iter() (T) |
| A custom sequence | A generator, function* with yield | IEnumerable<T> with yield return | A 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:
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}`);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}");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 callsnext()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:
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"]
| Method | Each item is | The collection afterwards |
|---|---|---|
.iter() | &T, a shared borrow | Unchanged and still yours |
.iter_mut() | &mut T, a mutable borrow | Changed in place, still yours |
.into_iter() | T, the value itself | Gone: 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| Line | Code | scoresowner | iter (&scores)shared borrow (&) | &mut scoresmutable borrow (&mut) | What happens |
|---|---|---|---|---|---|
| 1 | let mut scores = vec![72, 45, 91]; | ownsscores starts | |||
| 2 | let mut iter = scores.iter(); | scores alive | &iter (&scores) starts | iter borrows scores | |
| 3 | scores.push(60); | scores alive | iter (&scores) alive | &mut&mut scores starts | errorE0502: push needs &mut scores, but iter is still alive |
| 4 | println!("{:?}", iter.next()); | scores ends | iter (&scores) ends | Last 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.
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`);(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");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:
| Rust | What it does | TypeScript (iterator helper or array method) |
|---|---|---|
map(f) | Transforms each item | map(f) |
filter(f) | Keeps items where f returns true | filter(f) |
flat_map(f) | Turns each item into several and flattens them | flatMap(f) |
take(n) / skip(n) | The first n items / all but the first n | take(n) / drop(n) |
enumerate() | Pairs each item with its position | Arrays: entries(). Iterators: none |
zip(other) | Pairs items from two iterators | None built in |
rev() | Walks backwards | Arrays: toReversed() (eager). Iterators: none |
collect() | Builds a collection: Vec, String, HashMap, … | toArray(), new Map(...), new Set(...) |
sum() / count() | Adds up / counts the items | reduce((a, b) => a + b, 0) / none |
fold(init, f) | Combines all items into one value | reduce(f, init) |
find(f) | The first match, as an Option | find(f), undefined if none |
any(f) / all(f) | Does any / every item match? | some(f) / every(f) |
for_each(f) | Runs f on each item | forEach(f) |
| Rust | What it does | LINQ |
|---|---|---|
map(f) | Transforms each item | Select(f) |
filter(f) | Keeps items where f returns true | Where(f) |
flat_map(f) | Turns each item into several and flattens them | SelectMany(f) |
take(n) / skip(n) | The first n items / all but the first n | Take(n) / Skip(n) |
enumerate() | Pairs each item with its position | Index() (.NET 9+) or Select((x, i) => ...) |
zip(other) | Pairs items from two sequences | Zip(other) |
rev() | Walks backwards | Reverse(). 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 items | Sum() / Count() |
fold(init, f) | Combines all items into one value | Aggregate(init, f) |
find(f) | The first match, as an Option | FirstOrDefault(f) |
any(f) / all(f) | Does any / every item match? | Any(f) / All(f) |
for_each(f) | Runs f on each item | A 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:
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"));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"]);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 writemethod<string>()Method<string>(). Rust needs the::there so the<isn’t read as “less than”. - Only the part you care about:
Vec<_>asks for aVecand 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:
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);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);
}
}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>returnsSome(item)for the next item, orNonewhen the sequence is over. This one never ends, so it never returnsNone;takeis what stops it.- Everything else comes free.
map,filter,take,sumand the rest are default methods onIterator(default methods are covered in Traits), so they work onFibonaccithe moment it hasnext. Aforloop 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?
| What | When | Why | How |
|---|---|---|---|
.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 chain | You 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 loop | The 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 Iterator | You 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.
Is the point a side effect per item: printing, writing to a file, sending a message?
YesNoUse a
forloopfor_eachworks too, but a loop reads better and allowsbreakandcontinue.Do you need
return,?orbreakin the middle, or update several variables per item?YesNoUse a
forloopEarly exits and several pieces of state are clearer as plain statements.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.
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`);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.