Rust for Pythonistas

Lesson 8 of 26

Iterators and closures

In Python you turn a list into a new list with a comprehension. Rust uses a chain of calls for the same job. Read the chain top to bottom, like a pipeline:

xs.iter().filter(|x| **x > 0).map(|x| *x * 2).collect::<Vec<_>>()

That means "take the items, keep some, change them, build a new list". Each call is small, and the result of one call feeds the next one. Three things to know before you read the examples:

  • .iter() walks over a Vec but hands out references to the items, not the items themselves. That is why you see *x, &x and |&x| below. Read & as "borrowed" (lesson 13). One * gets you the value behind a reference.
  • |x| x * 2 is a closure: Python's lambda x: x * 2.
  • A chain is lazy, like a generator: nothing runs until something asks for a value. .collect(), .sum() or a for loop asks for them.

You will also meet .into_iter(). It hands out the items themselves and uses up the Vec (lesson 13). .iter() is the one you will read most.

A comprehension becomes a chain

The Python comprehension does three things in one line: loop, keep, change. In Rust each of those is a separate call, and the type of collect is written on the left. Hover the marked lines.

Python
numbers = [3, -1, 4, -2, 5]
doubled = [x * 2 for x in numbers if x > 0]
print(doubled)
Rust
fn main() {
    let numbers = vec![3, -1, 4, -2, 5];
    let doubled: Vec<i32> = numbers
        .iter()
        .filter(|x| **x > 0)
        .map(|x| *x * 2)
        .collect();
    println!("{:?}", doubled);
}
Output
[6, 8, 10]

sum, max, min and count

Some chains end in a number instead of a list. collect is then not needed, but sum still needs to know what kind of number to make.

Python
scores = [7, 12, 4]
print(sum(scores), max(scores), min(scores))
print(len([s for s in scores if s > 5]))
Rust
fn main() {
    let scores = vec![7, 12, 4];
    let total: i32 = scores.iter().sum();
    let top = scores.iter().max().unwrap();
    let low = scores.iter().min().unwrap();
    println!("{total} {top} {low}");
    let big = scores.iter().filter(|s| **s > 5).count();
    println!("{big}");
}
Output
23 12 4
2

enumerate and zip inside a for loop

enumerate and zip exist in Rust with the same names and the same meaning. Here the chain ends in a for loop instead of collect, so no Vec is built.

Python
names = ["ada", "bob"]
ages = [36, 41]
for i, (name, age) in enumerate(zip(names, ages), start=1):
    print(f"{i}. {name} is {age}")
Rust
fn main() {
    let names = vec!["ada", "bob"];
    let ages = vec![36, 41];
    for (i, (name, age)) in names.iter().zip(ages.iter()).enumerate() {
        println!("{}. {} is {}", i + 1, name, age);
    }
}
Output
1. ada is 36
2. bob is 41

Nothing runs until you ask

A chain is lazy. Building it costs nothing; the closures run when collect asks for the items. The same is true of a Python generator. A closure with braces can hold several lines, like a function body.

Python
def double(x):
    print(f"doubling {x}")
    return x * 2

chain = (double(x) for x in [1, 2, 3])
print("chain made")
print(list(chain))
Rust
fn main() {
    let numbers = vec![1, 2, 3];
    let chain = numbers.iter().map(|x| {
        println!("doubling {x}");
        *x * 2
    });
    println!("chain made");
    let values: Vec<i32> = chain.collect();
    println!("{:?}", values);
}
Output
chain made
doubling 1
doubling 2
doubling 3
[2, 4, 6]

any, all and rev

any and all answer a yes/no question about a whole list and stop as soon as they know the answer. rev walks a chain backwards. Neither builds a new list.

Python
words = ["a", "bb", "ccc"]
if any(len(w) > 2 for w in words):
    print("has a long word")
if all(len(w) > 0 for w in words):
    print("no empty words")
for w in reversed(words):
    print(w)
Rust
fn main() {
    let words = vec!["a", "bb", "ccc"];
    if words.iter().any(|w| w.len() > 2) {
        println!("has a long word");
    }
    if words.iter().all(|w| !w.is_empty()) {
        println!("no empty words");
    }
    for w in words.iter().rev() {
        println!("{w}");
    }
}
Output
has a long word
no empty words
ccc
bb
a

Where the Python analogy breaks

Cheat card

PythonRust
[x * 2 for x in xs]xs.iter().map(|x| x * 2).collect::<Vec<_>>()
[x for x in xs if x > 0]xs.iter().filter(|x| **x > 0).collect::<Vec<_>>()
lambda x: x * 2|x| x * 2
def f(x): print(x) return x * 2|x| { println!("{x}"); x * 2 }
sum(xs)let total: i32 = xs.iter().sum();
max(xs), min(xs)xs.iter().max(), xs.iter().min() // Option, lesson 11
sum(1 for x in xs if x > 0)xs.iter().filter(|x| **x > 0).count()
for i, x in enumerate(xs):for (i, x) in xs.iter().enumerate() {
for x, y in zip(a, b):for (x, y) in a.iter().zip(b.iter()) {
any(x > 0 for x in xs)xs.iter().any(|x| *x > 0)
all(x > 0 for x in xs)xs.iter().all(|x| *x > 0)
reversed(xs)xs.iter().rev()

← Vec and HashMap Structs and impl →