Start learning free

LESSON 277 OF 679 · TUPLES, SORTING & BUILT-INS

Enumerate and Zip in Rust

Lesson

TL ; DR:

enumerate() counts the items while you loop. zip() walks two vectors side by side.


let fruits = vec!["apple", "kiwi", "plum"];

let prices = vec![3, 1, 2];

for (i, fruit) in fruits.iter().enumerate() {
    println!("{}. {}", i + 1, fruit);
}

// prints 1. apple, 2. kiwi, 3. plum

for (fruit, price) in fruits.iter().zip(prices.iter()) {
    println!("{} {}", fruit, price);
}

// prints apple 3, kiwi 1, plum 2


Full lesson:

You have looped with for i in 0..meals.len(). Then meals[i] gave the item. As Vec & Iterators said, Rust prefers iterators. They give you both at once.

enumerate() gives each item together with its index. The loop unpacks the tuple into two names, as let (name, age) = pet does.

for (i, meal) in meals.iter().enumerate() {
    println!("{} {}", i, meal);
}

The index comes first. It starts at 0, so print i + 1 for a numbered list. The index is a usize.

a.iter().zip(b.iter()) walks two vectors side by side. It pairs the first item of a with the first item of b. Then it pairs the second items, and so on. Each pair is a tuple.

for (fruit, price) in fruits.iter().zip(prices.iter()) {
    println!("{} costs {}", fruit, price);
}

The items are references, because iter() borrows them. println! prints them as they are. For math, write *price.

zip stops at the end of the shorter vector. The extra items are skipped, with no error.

The two work together. Zip first, then call enumerate() on the result. Each item is then an index and a pair, so the names nest.

let pairs = fruits.iter().zip(prices.iter());
for (i, (fruit, price)) in pairs.enumerate() {
    println!("{}. {} costs {}", i + 1, fruit, price);
}

The two lines can also be one: for (i, (fruit, price)) in fruits.iter().zip(prices.iter()).enumerate().


Your task

A quiz show keeps its players in the vector players. Their points are in scores, in the same order.

First, print the players as a numbered list from 1, like 1. Ana. Use enumerate().

Then print each player with their points, like Ana has 12 points. Use zip().

Expected output:

1. Ana
2. Ben
3. Cleo
Ana has 12 points
Ben has 9 points
Cleo has 15 points
STEP 1 OF 4
    Ctrl + Enter to check