En bref. En Rust, un itérateur est une valeur qui sait donner l’élément suivant, et rien d’autre. map, filter et take ne parcourent rien : ils fabriquent un nouvel itérateur autour du précédent. Le parcours ne commence que lorsqu’un consommateur, comme collect, demande un élément. Cette paresse explique l’avertissement du titre, l’absence de liste intermédiaire, et le fait qu’une chaîne compile vers le même code machine qu’une boucle écrite à la main.
Le modèle en une phrase
Un itérateur est une valeur avec une méthode
next(). Un adaptateur (map,filter,take) emballe un itérateur dans un autre sans rien parcourir. Un consommateur (collect,sum, une bouclefor) appellenext(), et chaque appel tire un seul élément à travers toute la chaîne.
L’animation montre les deux moitiés du sujet : une chaîne qui ne s’exécute qu’à collect, un élément à la fois, puis les trois façons d’obtenir un itérateur à partir d’un vecteur.
In short. In Rust, an iterator is a value that knows how to give the next element, and nothing else. map, filter and take traverse nothing: they build a new iterator around the previous one. The traversal only starts when a consumer, such as collect, asks for an element. This laziness explains the warning in the title, the absence of any intermediate list, and the fact that a chain compiles to the same machine code as a hand-written loop.
The model in one sentence
An iterator is a value with a
next()method. An adapter (map,filter,take) wraps an iterator inside another one without traversing anything. A consumer (collect,sum, aforloop) callsnext(), and each call pulls a single element through the whole chain.
The animation shows both halves of the subject: a chain that only runs at collect, one element at a time, then the three ways to get an iterator from a vector.
let chaine = v.iter().map(|x| x * 10).filter(|x| x % 20 == 0).take(2);let r: Vec<i32> = chaine.collect();
vvaut[1, 2, 3, 4, 5]. Les quatre premières lignes construisent une chaîne :map,filterettakes'emboîtent l'un dans l'autre. Aucune closure n'est appelée. La chaîne est une valeur, qui décrit un travail à faire. (Dans le programme réel, chaque closure affiche son passage.)vis[1, 2, 3, 4, 5]. The first four lines build a chain:map,filterandtakenest inside one another. No closure is called. The chain is a value, describing work to be done. (In the real program, each closure prints as it runs.)collectest un consommateur : il appellenext()sur la chaîne. La demande remonte jusqu'à la source, qui donne1.mapen fait10,filterle rejette. Un seul élément a traversé toute la chaîne ;2n'a pas encore été lu.collectis a consumer: it callsnext()on the chain. The request travels up to the source, which gives1.mapturns it into10,filterrejects it. A single element has gone through the whole chain;2hasn't been read yet.filtern'a rien à rendre, donc il redemande un élément.2devient20, passe le filtre, ettakele compte : un sur deux.collectle range dans leVec. Il n'y a pas de liste intermédiaire entre les étages : les valeurs passent une à une.filterhas nothing to return, so it asks for another element.2becomes20, passes the filter, andtakecounts it: one out of two.collectstores it in theVec. There is no intermediate list between stages: values go through one at a time.3donne30, rejeté.4donne40, gardé :take(2)a ses deux éléments et répondNoneà la demande suivante.collects'arrête et rend[20, 40].5n'a jamais été lu, etmap 5ne s'affiche pas.3gives30, rejected.4gives40, kept:take(2)has its two elements and answersNoneto the next request.collectstops and returns[20, 40].5was never read, andmap 5isn't printed.
Un itérateur, c’est next()
Le trait Iterator ne demande qu’une méthode : next, qui rend Some(élément) tant qu’il en reste, puis None. Voici un itérateur écrit à la main, qui compte jusqu’à trois :
struct Compteur {
n: u32,
}
impl Iterator for Compteur {
type Item = u32;
fn next(&mut self) -> Option<u32> {
if self.n < 3 {
self.n += 1;
Some(self.n)
} else {
None
}
}
}
fn main() {
let mut c = Compteur { n: 0 };
println!("{:?}", c.next());
println!("{:?}", c.next());
println!("{:?}", c.next());
println!("{:?}", c.next());
let total: u32 = Compteur { n: 0 }.map(|x| x * x).sum();
println!("total : {total}");
}Some(1)
Some(2)
Some(3)
None
total : 14Deux choses à retenir. D’abord, l’itérateur ne contient pas les éléments : il contient de quoi calculer le suivant (ici, un compteur). Ensuite, écrire next suffit pour recevoir tout le reste : map, filter, sum et des dizaines d’autres méthodes sont fournies par le trait, et toutes sont construites sur next. Une boucle for aussi : elle appelle next() jusqu’à recevoir None.
Les adaptateurs ne font rien
Voici l’erreur de départ. Le programme veut afficher chaque élément, et utilise map pour ça :
fn main() {
let v = vec![1, 2, 3];
v.iter().map(|x| {
println!("vu {x}");
x * 2
});
println!("fin");
}Il compile, avec un avertissement :
warning: unused `Map` that must be used
--> paresse.rs:3:5
|
3 | / v.iter().map(|x| {
4 | | println!("vu {x}");
5 | | x * 2
6 | | });
| |______^
|
= note: iterators are lazy and do nothing unless consumedEt à l’exécution, il n’affiche qu’une ligne :
finAucun « vu » n’apparaît. map n’a pas parcouru le vecteur : il a rendu une valeur de type Map, qui contient l’itérateur de départ et la closure, puis cette valeur a été jetée au point-virgule. La closure n’a jamais été appelée, parce que personne n’a appelé next().
Les méthodes d’Iterator se rangent donc en deux familles :
| Famille | Exemples | Ce que fait l’appel |
|---|---|---|
| Adaptateurs | map, filter, take, skip, zip, enumerate | rend un nouvel itérateur, ne lit aucun élément |
| Consommateurs | collect, sum, count, fold, for_each, la boucle for | appelle next() jusqu’à la fin (ou jusqu’à avoir sa réponse) |
Pour un effet de bord comme un affichage, la bonne écriture est une boucle for, ou for_each en fin de chaîne.
Un élément à la fois
Quand le consommateur arrive, dans quel ordre le travail se fait-il ? Ce programme le montre : chaque closure signale son passage.
fn main() {
let v = vec![1, 2, 3, 4, 5];
let chaine = v
.iter()
.map(|x| {
println!(" map {x}");
x * 10
})
.filter(|x| {
println!(" filter {x}");
x % 20 == 0
})
.take(2);
println!("chaîne construite");
let r: Vec<i32> = chaine.collect();
println!("{r:?}");
}chaîne construite
map 1
filter 10
map 2
filter 20
map 3
filter 30
map 4
filter 40
[20, 40]Trois faits se lisent dans cette sortie.
- « chaîne construite » s’affiche en premier : les quatre lignes de la chaîne n’ont rien exécuté.
- Les lignes
mapetfilteralternent. Le programme ne fait pas « tous lesmap, puis tous lesfilter» : chaque élément traverse toute la chaîne avant que le suivant soit lu. - Il n’y a pas de
map 5. Dès quetake(2)a ses deux éléments, il répondNone, et la source n’est plus interrogée.
La demande part du bas et remonte ; la valeur redescend :
demande : next() réponse
collect ─────────────────────────────┐
▼
take(2) « il m'en faut encore un » ▲ Some(20)
│ │
▼ │
filter « un élément divisible par 20 » ▲ 20 gardé (10 rejeté :
│ │ filter redemande)
▼ │
map « un élément, multiplié par 10 » ▲ 10, puis 20
│ │
▼ │
v.iter() « l'élément suivant du Vec » ▲ &1, puis &2Conséquence pratique : entre map et filter, il n’existe aucun vecteur intermédiaire. La chaîne n’alloue rien ; seul collect alloue, pour le résultat.
La chaîne est une valeur
Si la chaîne ne contient pas les éléments, que contient-elle ? On peut le mesurer :
fn main() {
let v = vec![1, 2, 3, 4, 5];
let it = v.iter();
println!("iter : {} octets", std::mem::size_of_val(&it));
let chaine = v.iter().map(|x| x * 10).filter(|x| x % 20 == 0).take(2);
println!("iter.map.filter.take : {} octets", std::mem::size_of_val(&chaine));
println!("{}", std::any::type_name_of_val(&chaine));
}iter : 16 octets
iter.map.filter.take : 24 octets
core::iter::adapters::take::Take<core::iter::adapters::filter::Filter<core::iter::adapters::map::Map<core::slice::iter::Iter<'_, i32>, taille::main::{{closure}}>, taille::main::{{closure}}>>L’itérateur de départ fait 16 octets : deux pointeurs, la position courante et la fin. La chaîne complète en fait 24 : ces deux pointeurs, plus le compteur de take. map et filter n’ajoutent rien, parce que leurs closures ne capturent aucune variable et occupent donc zéro octet.
Le type affiché est la partie importante. Sans les chemins de modules, il se lit ainsi :
Take< Filter< Map< Iter<i32>, closure n°1 >, closure n°2 > >
│ │ │ │
│ │ │ └─ la source : deux pointeurs dans le Vec
│ │ └───────── contient la source et sa closure
│ └─────────────── contient le Map et sa closure
└────────────────────── contient le Filter et un compteurChaque adaptateur est une struct qui contient le précédent, et chaque closure a son propre type. Toute la chaîne est donc décrite dans un seul type, connu à la compilation. C’est ce qui rend la section suivante possible.
Zéro coût, vérifié
Puisque le compilateur connaît le type exact de chaque étage, il connaît aussi le code exact de chaque next(), et peut l’intégrer sur place (inlining). Pour le vérifier, deux fonctions qui font la somme des carrés des nombres pairs, l’une avec une boucle indexée, l’autre avec une chaîne :
#[unsafe(no_mangle)]
pub fn boucle(v: &[i32]) -> i32 {
let mut total = 0;
for i in 0..v.len() {
if v[i] % 2 == 0 {
total += v[i] * v[i];
}
}
total
}
#[unsafe(no_mangle)]
pub fn chaine(v: &[i32]) -> i32 {
v.iter().filter(|x| **x % 2 == 0).map(|x| x * x).sum()
}Compilées avec rustc -O --emit asm (rustc 1.100, aarch64), puis en comptant dans l’assembleur produit :
boucle | chaine | |
|---|---|---|
Instructions, avec -O | 85 | 85 |
Appels de fonction, avec -O | 0 | 0 |
| Vectorisée (NEON) | oui | oui |
Les deux fonctions ont le même nombre d’instructions, et aucune n’appelle next, filter ou une closure : tout a été intégré, puis vectorisé. Les seules différences entre les deux listings sont le choix des registres et l’ordre de deux instructions. C’est le sens de « abstraction à coût zéro » : la chaîne ne coûte rien de plus que la boucle qu’on aurait écrite à sa place.
Cette égalité dépend de l’optimiseur. Sans -O, en mode debug, la même mesure donne autre chose :
boucle | chaine | |
|---|---|---|
Instructions, sans -O | 105 | 8 |
Appels de fonction, sans -O | 8 | 4 |
chaine ne fait que 8 instructions parce qu’elle délègue tout : elle appelle iter, filter, map et sum, qui sont de vraies fonctions non intégrées, chacune appelant les suivantes à chaque élément. Un programme compilé sans optimisation paie donc bien le prix des étages. Mesurer des itérateurs en mode debug ne dit rien de leur coût réel.
collect a besoin d’un type
collect est le consommateur le plus courant, et celui qui produit le plus d’erreurs. La première :
fn main() {
let v = vec![1, 2, 3];
let doubles = v.iter().map(|x| x * 2).collect();
println!("{}", doubles.len());
}error[E0282]: type annotations needed
--> annot.rs:3:9
|
3 | let doubles = v.iter().map(|x| x * 2).collect();
| ^^^^^^^
4 | println!("{}", doubles.len());
| ------- type must be known at this point
|
help: consider giving `doubles` an explicit type
|
3 | let doubles: Vec<_> = v.iter().map(|x| x * 2).collect();
| ++++++++collect peut construire un Vec, une HashMap, une String, un HashSet : tout type qui implémente FromIterator. Rien dans la chaîne ne dit lequel, donc il faut l’écrire. Vec<_> suffit : le tiret bas laisse le compilateur déduire le type des éléments. L’autre écriture, utile en milieu d’expression, est .collect::<Vec<_>>().
La seconde erreur vient du type des éléments :
fn main() {
let v = vec![1, 2, 3];
let doubles: Vec<i32> = v.iter().filter(|x| **x > 1).collect();
}error[E0277]: a value of type `Vec<i32>` cannot be built from an iterator over elements of type `&{integer}`
--> refs.rs:3:58
|
3 | let doubles: Vec<i32> = v.iter().filter(|x| **x > 1).collect();
| ^^^^^^^ value of type `Vec<i32>` cannot be built from `std::iter::Iterator<Item=&{integer}>`
|
help: the trait `FromIterator<&{integer}>` is not implemented for `Vec<i32>`
but trait `FromIterator<i32>` is implemented for itv.iter() emprunte le vecteur, donc il donne des références : des &i32. filter garde ou rejette, mais ne change pas le type. collect reçoit des &i32 et on lui demande un Vec<i32> : il ne sait pas faire. La correction la plus courante est copied(), qui transforme chaque &i32 en i32 :
let grands: Vec<i32> = v.iter().copied().filter(|x| *x > 1).collect();[2, 3]copied() vaut pour les types Copy. Pour une String ou tout autre type Clone, c’est cloned(), qui clone chaque élément. Et si le vecteur d’origine n’est plus utile, la section suivante donne une troisième voie.
iter, iter_mut, into_iter
Un vecteur fournit trois itérateurs, qui correspondent aux trois façons d’accéder à une valeur en Rust : la lire, la modifier, la posséder.
fn main() {
let mut v = vec![String::from("a"), String::from("b")];
for s in v.iter() {
println!("iter : {s}");
}
for s in v.iter_mut() {
s.push('!');
}
println!("iter_mut : {v:?}");
for s in v.into_iter() {
println!("into_iter : {s}");
}
}iter : a
iter : b
iter_mut : ["a!", "b!"]
into_iter : a!
into_iter : b!
| Méthode | Forme courte | Chaque tour reçoit | Après la boucle |
|---|---|---|---|
v.iter() | for s in &v | &String | v est intact |
v.iter_mut() | for s in &mut v | &mut String | v est modifié |
v.into_iter() | for s in v | String | v a été déplacé |
La forme courte de la dernière ligne est la source d’une erreur classique. for s in v ne mentionne aucune méthode, mais il appelle into_iter() et consomme le vecteur :
fn main() {
let v = vec![String::from("a"), String::from("b")];
for s in v {
println!("{s}");
}
println!("{}", v.len());
}error[E0382]: borrow of moved value: `v`
--> deplace.rs:6:20
|
2 | let v = vec![String::from("a"), String::from("b")];
| - move occurs because `v` has type `Vec<String>`, which does not implement the `Copy` trait
3 | for s in v {
| - `v` moved due to this implicit call to `.into_iter()`
...
6 | println!("{}", v.len());
| ^ value borrowed here after moveLe message nomme l’appel caché : this implicit call to .into_iter(). La suite de la sortie propose la correction, for s in &v, qui emprunte au lieu de déplacer. C’est le move du premier article de la série, déclenché ici par une boucle.
Ce que l’image cache
- Un
collectau milieu d’une chaîne alloue. Écrire.collect::<Vec<_>>()puis repartir avec.iter()crée un vecteur intermédiaire que la paresse rendait inutile. Tant que la suite est une chaîne, on peut continuer sans collecter. dyn Iteratorcoupe l’intégration. UnBox<dyn Iterator<Item = i32>>efface le type de la chaîne : chaquenext()devient un appel dynamique, que le compilateur ne peut ni intégrer ni vectoriser. C’est parfois le bon choix (rendre des itérateurs de types différents), mais le zéro coût ne s’applique plus.impl Iteratoren type de retour garde le type concret.- Un itérateur peut être infini.
(1..)ne s’arrête jamais, et c’est sans danger tant qu’untake, unfindou untake_whileborne la demande. La paresse est ce qui rend ces écritures possibles. - Tous les consommateurs ne lisent pas tout.
find,any,alletpositions’arrêtent dès qu’ils ont leur réponse, commetakedans l’animation. - Une boucle peut cacher un parcours par tour.
s.chars().nth(i)repart du début de la chaîne à chaque appel ; dans une boucle suri, le coût devient quadratique. Un seul parcours avecchars().enumerate()fait le même travail. - Un itérateur avance, il ne revient pas. Une fois consommé, il est vide : pour parcourir deux fois, il faut en redemander un (
v.iter()une seconde fois), ce qui ne coûte rien. - Réécrire une chaîne en boucle « pour la performance » ne gagne rien en compilation optimisée, comme le montre la mesure plus haut. La boucle indexée garde même des vérifications de bornes que le compilateur doit prouver inutiles, alors que l’itérateur n’en a pas.
Pour aller plus loin
- Volume 9, numéro 01 de The Rust Loop, Itérateurs & abstractions zéro-coût, qui part de
next()et va jusqu’à la lecture de l’assembleur produit (lien en bas de page). - Articles précédents : le move (E0382), l’emprunt (E0502), les slices, les lifetimes (E0106), l’élision,
'static, enums et match (E0004), Option et unwrap, newtype et type-state (E0599), Result et?(E0277), thiserror et anyhow (E0119), panic et invariants, traits et generics (E0369), dyn et vtable (E0038), règle de l’orphelin (E0117), Box et types récursifs (E0072), Rc et Arc (E0277), Cell et RefCell, threads et move (E0373), Send, Sync etArc<Mutex<T>>(E0277), les canaux mpsc (E0382), Future et .await (E0728), les fonctions colorées et Send, annuler et sélectionner. - La documentation du trait
Iterator, avec la liste complète des adaptateurs et des consommateurs - Le Rust Book, chapitre 13.2 : les itérateurs, et 13.4 : boucles contre itérateurs
FromIterator, le trait derrièrecollect, etIntoIterator, le trait derrière la bouclefor
An iterator is next()
The Iterator trait asks for a single method: next, which returns Some(element) as long as there are any left, then None. Here is a hand-written iterator that counts to three:
struct Compteur {
n: u32,
}
impl Iterator for Compteur {
type Item = u32;
fn next(&mut self) -> Option<u32> {
if self.n < 3 {
self.n += 1;
Some(self.n)
} else {
None
}
}
}
fn main() {
let mut c = Compteur { n: 0 };
println!("{:?}", c.next());
println!("{:?}", c.next());
println!("{:?}", c.next());
println!("{:?}", c.next());
let total: u32 = Compteur { n: 0 }.map(|x| x * x).sum();
println!("total : {total}");
}Some(1)
Some(2)
Some(3)
None
total : 14Two things to remember. First, the iterator does not hold the elements: it holds what it needs to compute the next one (here, a counter). Second, writing next is enough to receive everything else: map, filter, sum and dozens of other methods are provided by the trait, and all of them are built on next. So is a for loop: it calls next() until it receives None.
Adapters do nothing
Here is the starting mistake. The program wants to print each element, and uses map for that:
fn main() {
let v = vec![1, 2, 3];
v.iter().map(|x| {
println!("vu {x}");
x * 2
});
println!("fin");
}It compiles, with a warning:
warning: unused `Map` that must be used
--> paresse.rs:3:5
|
3 | / v.iter().map(|x| {
4 | | println!("vu {x}");
5 | | x * 2
6 | | });
| |______^
|
= note: iterators are lazy and do nothing unless consumedAnd when run, it prints a single line:
finNo “vu” line appears. map did not traverse the vector: it returned a value of type Map, which holds the starting iterator and the closure, and that value was thrown away at the semicolon. The closure was never called, because nobody called next().
So the methods of Iterator fall into two families:
| Family | Examples | What the call does |
|---|---|---|
| Adapters | map, filter, take, skip, zip, enumerate | returns a new iterator, reads no element |
| Consumers | collect, sum, count, fold, for_each, the for loop | calls next() until the end (or until it has its answer) |
For a side effect such as printing, the right spelling is a for loop, or for_each at the end of the chain.
One element at a time
When the consumer arrives, in what order does the work happen? This program shows it: each closure reports when it runs.
fn main() {
let v = vec![1, 2, 3, 4, 5];
let chaine = v
.iter()
.map(|x| {
println!(" map {x}");
x * 10
})
.filter(|x| {
println!(" filter {x}");
x % 20 == 0
})
.take(2);
println!("chaîne construite");
let r: Vec<i32> = chaine.collect();
println!("{r:?}");
}chaîne construite
map 1
filter 10
map 2
filter 20
map 3
filter 30
map 4
filter 40
[20, 40]Three facts can be read from this output.
- “chaîne construite” (chain built) is printed first: the four lines of the chain ran nothing.
- The
mapandfilterlines alternate. The program does not do “all themaps, then all thefilters”: each element goes through the whole chain before the next one is read. - There is no
map 5. As soon astake(2)has its two elements, it answersNone, and the source is no longer asked.
The request starts at the bottom and travels up; the value comes back down:
request: next() answer
collect ─────────────────────────────┐
▼
take(2) "I need one more" ▲ Some(20)
│ │
▼ │
filter "an element divisible by 20" ▲ 20 kept (10 rejected:
│ │ filter asks again)
▼ │
map "an element, multiplied by 10" ▲ 10, then 20
│ │
▼ │
v.iter() "the next element of the Vec" ▲ &1, then &2The practical consequence: between map and filter, no intermediate vector exists. The chain allocates nothing; only collect allocates, for the result.
The chain is a value
If the chain does not hold the elements, what does it hold? It can be measured:
fn main() {
let v = vec![1, 2, 3, 4, 5];
let it = v.iter();
println!("iter : {} octets", std::mem::size_of_val(&it));
let chaine = v.iter().map(|x| x * 10).filter(|x| x % 20 == 0).take(2);
println!("iter.map.filter.take : {} octets", std::mem::size_of_val(&chaine));
println!("{}", std::any::type_name_of_val(&chaine));
}iter : 16 octets
iter.map.filter.take : 24 octets
core::iter::adapters::take::Take<core::iter::adapters::filter::Filter<core::iter::adapters::map::Map<core::slice::iter::Iter<'_, i32>, taille::main::{{closure}}>, taille::main::{{closure}}>>The starting iterator is 16 bytes (“octets”): two pointers, the current position and the end. The complete chain is 24: those two pointers, plus the counter of take. map and filter add nothing, because their closures capture no variable and therefore take zero bytes.
The printed type is the important part. Without the module paths, it reads like this:
Take< Filter< Map< Iter<i32>, closure #1 >, closure #2 > >
│ │ │ │
│ │ │ └─ the source: two pointers into the Vec
│ │ └───────── holds the source and its closure
│ └─────────────── holds the Map and its closure
└────────────────────── holds the Filter and a counterEach adapter is a struct that contains the previous one, and each closure has its own type. The whole chain is therefore described in a single type, known at compile time. That is what makes the next section possible.
Zero cost, checked
Since the compiler knows the exact type of each stage, it also knows the exact code of each next(), and can inline it. To check, here are two functions that sum the squares of the even numbers, one with an indexed loop, the other with a chain:
#[unsafe(no_mangle)]
pub fn boucle(v: &[i32]) -> i32 {
let mut total = 0;
for i in 0..v.len() {
if v[i] % 2 == 0 {
total += v[i] * v[i];
}
}
total
}
#[unsafe(no_mangle)]
pub fn chaine(v: &[i32]) -> i32 {
v.iter().filter(|x| **x % 2 == 0).map(|x| x * x).sum()
}Compiled with rustc -O --emit asm (rustc 1.100, aarch64), then counted in the generated assembly:
boucle (loop) | chaine (chain) | |
|---|---|---|
Instructions, with -O | 85 | 85 |
Function calls, with -O | 0 | 0 |
| Vectorised (NEON) | yes | yes |
Both functions have the same number of instructions, and neither calls next, filter or a closure: everything was inlined, then vectorised. The only differences between the two listings are the choice of registers and the order of two instructions. That is the meaning of “zero-cost abstraction”: the chain costs nothing more than the loop you would have written in its place.
This equality depends on the optimiser. Without -O, in debug mode, the same measurement gives something else:
boucle (loop) | chaine (chain) | |
|---|---|---|
Instructions, without -O | 105 | 8 |
Function calls, without -O | 8 | 4 |
chaine is only 8 instructions because it delegates everything: it calls iter, filter, map and sum, which are real, non-inlined functions, each calling the next ones for every element. A program compiled without optimisation does pay for the stages. Measuring iterators in debug mode says nothing about their real cost.
collect needs a type
collect is the most common consumer, and the one that produces the most errors. The first one:
fn main() {
let v = vec![1, 2, 3];
let doubles = v.iter().map(|x| x * 2).collect();
println!("{}", doubles.len());
}error[E0282]: type annotations needed
--> annot.rs:3:9
|
3 | let doubles = v.iter().map(|x| x * 2).collect();
| ^^^^^^^
4 | println!("{}", doubles.len());
| ------- type must be known at this point
|
help: consider giving `doubles` an explicit type
|
3 | let doubles: Vec<_> = v.iter().map(|x| x * 2).collect();
| ++++++++collect can build a Vec, a HashMap, a String, a HashSet: any type that implements FromIterator. Nothing in the chain says which one, so it has to be written. Vec<_> is enough: the underscore lets the compiler infer the element type. The other spelling, handy in the middle of an expression, is .collect::<Vec<_>>().
The second error comes from the item type:
fn main() {
let v = vec![1, 2, 3];
let doubles: Vec<i32> = v.iter().filter(|x| **x > 1).collect();
}error[E0277]: a value of type `Vec<i32>` cannot be built from an iterator over elements of type `&{integer}`
--> refs.rs:3:58
|
3 | let doubles: Vec<i32> = v.iter().filter(|x| **x > 1).collect();
| ^^^^^^^ value of type `Vec<i32>` cannot be built from `std::iter::Iterator<Item=&{integer}>`
|
help: the trait `FromIterator<&{integer}>` is not implemented for `Vec<i32>`
but trait `FromIterator<i32>` is implemented for itv.iter() borrows the vector, so it yields references: &i32 items. filter keeps or rejects, but does not change the type. collect receives &i32 items and is asked for a Vec<i32>: it cannot do that. The most common fix is copied(), which turns each &i32 into an i32:
let grands: Vec<i32> = v.iter().copied().filter(|x| *x > 1).collect();[2, 3]copied() works for Copy types. For a String or any other Clone type, use cloned(), which clones each element. And if the original vector is no longer needed, the next section gives a third way.
iter, iter_mut, into_iter
A vector provides three iterators, matching the three ways to access a value in Rust: read it, modify it, own it.
fn main() {
let mut v = vec![String::from("a"), String::from("b")];
for s in v.iter() {
println!("iter : {s}");
}
for s in v.iter_mut() {
s.push('!');
}
println!("iter_mut : {v:?}");
for s in v.into_iter() {
println!("into_iter : {s}");
}
}iter : a
iter : b
iter_mut : ["a!", "b!"]
into_iter : a!
into_iter : b!
| Method | Short form | Each turn gets | After the loop |
|---|---|---|---|
v.iter() | for s in &v | &String | v is intact |
v.iter_mut() | for s in &mut v | &mut String | v is modified |
v.into_iter() | for s in v | String | v has been moved |
The short form on the last row is the source of a classic error. for s in v mentions no method, but it calls into_iter() and consumes the vector:
fn main() {
let v = vec![String::from("a"), String::from("b")];
for s in v {
println!("{s}");
}
println!("{}", v.len());
}error[E0382]: borrow of moved value: `v`
--> deplace.rs:6:20
|
2 | let v = vec![String::from("a"), String::from("b")];
| - move occurs because `v` has type `Vec<String>`, which does not implement the `Copy` trait
3 | for s in v {
| - `v` moved due to this implicit call to `.into_iter()`
...
6 | println!("{}", v.len());
| ^ value borrowed here after moveThe message names the hidden call: this implicit call to .into_iter(). The rest of the output suggests the fix, for s in &v, which borrows instead of moving. This is the move from the first article of the series, triggered here by a loop.
What the picture hides
- A
collectin the middle of a chain allocates. Writing.collect::<Vec<_>>()and then starting again with.iter()creates an intermediate vector that laziness made unnecessary. As long as what follows is a chain, you can carry on without collecting. dyn Iteratorstops inlining. ABox<dyn Iterator<Item = i32>>erases the type of the chain: eachnext()becomes a dynamic call, which the compiler can neither inline nor vectorise. It is sometimes the right choice (returning iterators of different types), but zero cost no longer applies.impl Iteratoras a return type keeps the concrete type.- An iterator can be infinite.
(1..)never stops, and that is harmless as long as atake, afindor atake_whilebounds the demand. Laziness is what makes this possible. - Not every consumer reads everything.
find,any,allandpositionstop as soon as they have their answer, liketakein the animation. - A loop can hide one traversal per turn.
s.chars().nth(i)starts again from the beginning of the string on every call; in a loop overi, the cost becomes quadratic. A single pass withchars().enumerate()does the same work. - An iterator moves forward, never back. Once consumed, it is empty: to traverse twice, ask for another one (
v.iter()a second time), which costs nothing. - Rewriting a chain as a loop “for performance” gains nothing in an optimised build, as the measurement above shows. The indexed loop even keeps bounds checks that the compiler has to prove unnecessary, whereas the iterator has none.
Going further
- Volume 9, issue 01 of The Rust Loop, Iterators & zero-cost abstractions, which starts from
next()and goes all the way to reading the generated assembly (link at the bottom of the page). - Previous articles: move (E0382), borrowing (E0502), slices, lifetimes (E0106), elision,
'static, enums and match (E0004), Option and unwrap, newtype and type-state (E0599), Result and?(E0277), thiserror and anyhow (E0119), panic and invariants, traits and generics (E0369), dyn and the vtable (E0038), the orphan rule (E0117), Box and recursive types (E0072), Rc and Arc (E0277), Cell and RefCell, threads and move (E0373), Send, Sync andArc<Mutex<T>>(E0277), mpsc channels (E0382), Future and .await (E0728), colored functions and Send, cancel and select. - The
Iteratortrait documentation, with the full list of adapters and consumers - The Rust Book, chapter 13.2: iterators, and 13.4: loops vs. iterators
FromIterator, the trait behindcollect, andIntoIterator, the trait behind theforloop