Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

Rust Iterators


Share

Iterators

An iterator gives you the items of a collection, like a vector, one at a time.

You have already used iterators: every time you loop through a vector with for, Rust uses an iterator for you.

Iterators also have useful methods that let you change, filter and add up items with very little code.


The iter() Method

Call iter() on a vector to get an iterator. Each call to next() returns the next item, wrapped in Some. When there are no more items, next() returns None:

Example

let fruits = vec!["apple", "banana", "cherry"];
let mut items = fruits.iter();

println!("{:?}", items.next());
println!("{:?}", items.next());
println!("{:?}", items.next());
println!("{:?}", items.next());
Try it Yourself »

next() returns an Option, because there might not be a next item. The iterator must be mut, because it changes each time it moves to the next item.


Loop with an Iterator

A for loop calls next() for you, until it gets None. The enumerate() method adds an index number to each item:

Example

let players = vec!["John", "Liam", "Jenny"];

for (index, player) in players.iter().enumerate() {
  println!("{}: {}", index, player);
}
Try it Yourself »

enumerate() gives you pairs of (index, item). The loop unpacks each pair into two variables, just like a tuple.



Change Items with map()

map() uses a closure to change each item. Then collect() gathers the results into a new vector:

Example

let prices = vec![10, 20, 30];
let doubled: Vec<i32> = prices.iter().map(|x| x * 2).collect();
println!("{:?}", doubled);
Try it Yourself »

The original prices vector does not change.

collect() Needs a Type

collect() can create many kinds of collections, so you must tell Rust which one you want. If you forget the type, you get an error:

Example

let prices = vec![10, 20, 30];
let doubled = prices.iter().map(|x| x * 2).collect(); // Error
println!("{:?}", doubled);
Try it Yourself »

Fix it by writing the type after the variable name: let doubled: Vec<i32>.


Keep Some Items with filter()

filter() keeps only the items where the closure returns true:

Example

let numbers = vec![1, 2, 3, 4, 5, 6];
for n in numbers.iter().filter(|x| *x % 2 == 0) {
  println!("{}", n);
}
Try it Yourself »

Just like retain() in the Closures chapter, filter() gives the closure a reference to each item, so we write *x. The for loop then prints the items that are left.


Sum and Count

sum() adds all the items together, and count() returns how many items there are:

Example

let scores = vec![50, 75, 100];
let total: i32 = scores.iter().sum();
let count = scores.iter().count();

println!("Total: {}", total);
println!("Count: {}", count);
Try it Yourself »

Just like collect(), sum() needs to know the type of the result, so we write total: i32.

Note: map() and filter() do nothing on their own. They only run when something asks for the items, like collect(), sum() or a for loop.


Common Iterator Methods

MethodDescription
iter()Creates an iterator that borrows each item
next()Returns the next item in Some, or None when there are no more items
enumerate()Adds an index number to each item
map()Changes each item with a closure
filter()Keeps only the items where the closure returns true
collect()Gathers the items into a collection, like a Vec
sum()Adds all the items together
count()Returns the number of items


Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.