Rust for Pythonistas

Lesson 7 of 26

Vec and HashMap

A Python list is a Vec in Rust (short for vector). You write vec![1, 2, 3] for a literal, and every item has the same type. A Python dict is a HashMap. Both grow and shrink while the program runs, so both need mut before you can add to them.

One difference that bites people: a HashMap has no order. Python dicts keep insertion order; a Rust HashMap does not, and the order can change from run to run. So never print a table by looping over a HashMap. Sort the keys first, or use a BTreeMap, which keeps its keys sorted.

You will see & a lot here. Read it as "borrowed: look at it, do not take it." Lesson 13 explains the rule behind it; for now, seeing & means the data stays where it is.

A list is a Vec

The four things you do with a list all have a Rust version. Note that len and sort are method calls here, so the list comes first.

Python
nums = [3, 1, 2]
nums.append(4)
print(len(nums))
print(nums[0])
nums.sort()
print(nums)
Rust
fn main() {
    let mut nums = vec![3, 1, 2];
    nums.push(4);
    println!("{}", nums.len());
    println!("{}", nums[0]);
    nums.sort();
    println!("{:?}", nums);
}
Output
4
3
[1, 2, 3, 4]

Building a Vec with Vec::new()

Vec::new() is []. Rust needs to be told what will go in it, which is what the : Vec<i32> is for: "a Vec of i32". Reading it out loud helps: Vec<String> is a list of strings.

Python
squares = []
for n in range(1, 6):
    squares.append(n * n)
print(squares)
total = 0
for n in squares:
    total += n
print(total)
if 25 in squares:
    print("yes")
Rust
fn main() {
    let mut squares: Vec<i32> = Vec::new();
    for n in 1..=5 {
        squares.push(n * n);
    }
    println!("{squares:?}");
    let mut total = 0;
    for n in &squares {
        total += n;
    }
    println!("{total}");
    if squares.contains(&25) {
        println!("yes");
    }
}
Output
[1, 4, 9, 16, 25]
55
yes

Slices and indexing

A slice &temps[1..3] is temps[1:3]: it starts at 1 and stops before 3. The & means middle points into temps instead of copying it, so it stays cheap for big lists.

Indexing a Vec past its end is not a catchable exception. It panics and the program stops right there. Python raises IndexError and you can catch it. If an index might be too big, Rust has temps.get(9), which gives Some(value) or None instead of crashing. Option is lesson 11.

Python
temps = [12, 15, 9, 21]
print(temps[1:3])
print(temps[0])
print(len(temps))
Rust
fn main() {
    let temps = vec![12, 15, 9, 21];
    let middle = &temps[1..3];
    println!("{middle:?}");
    println!("{}", temps[0]);
    println!("{}", temps.len());
}
Output
[15, 9]
12
4

A dict is a HashMap

HashMap lives in the standard library, so the file starts with a use line. It plays the role of from collections import ... in Python.

Python
ages = {"ada": 36, "bob": 41}
ages["cy"] = 29
print(len(ages))
print(ages["bob"])
if "ada" in ages:
    print("has ada")
del ages["bob"]
print(len(ages))
Rust
use std::collections::HashMap;

fn main() {
    let mut ages: HashMap<&str, i32> = HashMap::new();
    ages.insert("ada", 36);
    ages.insert("bob", 41);
    ages.insert("cy", 29);
    println!("{}", ages.len());
    println!("{}", ages["bob"]);
    if ages.contains_key("ada") {
        println!("has ada");
    }
    ages.remove("bob");
    println!("{}", ages.len());
}
Output
3
41
has ada
2

Counting words, and why map order is random

Counting items is the most common map job, so Rust gives it one line: *counts.entry(word).or_insert(0) += 1. It does what counts[word] = counts.get(word, 0) + 1 does in Python, or what Counter does.

This example uses BTreeMap, the sorted cousin of HashMap. Both count the same way. The difference is printing: a HashMap hands its keys out in a different order on every run, so the same table would look different each time. A BTreeMap always goes from smaller key to bigger key, which is what sorted(counts) gives you in Python. If you must print a plain HashMap, sort the keys first.

When you loop over a map you get a tuple per pair: (key, value). A Rust tuple is a small fixed group of values, written (1, "a"), like a Python tuple. You reach the parts with .0 and .1, or unpack them in the loop as below.

Python
from collections import Counter

words = ["red", "blue", "red", "green", "red"]
counts = Counter(words)
print(len(counts))
for w in sorted(counts):
    print(f"{w}: {counts[w]}")
Rust
use std::collections::BTreeMap;

fn main() {
    let words = vec!["red", "blue", "red", "green", "red"];
    let mut counts: BTreeMap<&str, i32> = BTreeMap::new();
    for w in &words {
        *counts.entry(*w).or_insert(0) += 1;
    }
    println!("{}", counts.len());
    for (w, n) in &counts {
        println!("{w}: {n}");
    }
}
Output
3
blue: 1
green: 1
red: 3

Where the Python analogy breaks

Cheat card

PythonRust
nums = [1, 2, 3]let nums = vec![1, 2, 3];
nums = []let mut nums: Vec<i32> = Vec::new();
nums.append(4)nums.push(4);
len(nums)nums.len()
nums.sort()nums.sort();
nums[1:3]&nums[1..3]
x in numsnums.contains(&x)
for x in nums:for x in &nums {
d["a"] = 1d.insert("a", 1);
d.get("a")d.get("a") // Some(v) or None
del d["a"]d.remove("a");
Counter(xs)*counts.entry(x).or_insert(0) += 1;

← if, loops and ranges Iterators and closures →