Blog

Part 13 · Collections in Rust: Vec, HashMap, HashSet, BTreeMap and VecDeque

Rust’s standard library has a small set of collections that cover most programs. This part shows Vec, HashMap and its entry API, HashSet, BTreeMap and VecDeque, what each one is good at, and how to pick.

A program rarely works with one value. It works with a list of orders, a count per word, a set of users who logged in today, a queue of jobs. Rust’s standard library has a small set of collections for these, and most programs use only a few of them.

This part covers the everyday Vec methods, then HashMap and its entry API, HashSet, BTreeMap and VecDeque, and ends with a table of which one to pick. Lookups return an Option, so it leans on Part 11. Ownership from Part 6 and the Vec buffer from Part 8 come back too. Every program here was run on Rust 1.95, and its output is pasted from the run.

Try this first

A HashMap stores values by key. Here the key is a name and the value is an age. Decide what this prints:

use std::collections::HashMap;

fn main() {
    let mut ages = HashMap::new();
    ages.insert("Ana", 31);
    let next_year = ages.get("Ana") + 1;
    println!("Ana will be {next_year}");
}

It doesn’t compile:

error[E0369]: cannot add `{integer}` to `Option<&{integer}>`
 --> src/main.rs:6:37
  |
6 |     let next_year = ages.get("Ana") + 1;
  |                     --------------- ^ - {integer}
  |                     |
  |                     Option<&{integer}>

In many languages, ages.get("Ana") gives you 31, or null if Ana isn’t there. In Rust it gives you Option<&i32>: Some(&31) if the key is there, and None if it isn’t. You can’t add 1 to “maybe a number”. You have to say what happens when the key is missing first.

The & means get lends you the value inside the map instead of copying it out. Every collection in this part works this way: asking for something that might not be there returns an Option.

Vec: the methods you’ll use every day

You’ve met Vec already. It’s a growable list, stored in one buffer on the heap (Part 8 showed the buffer growing). Here are the methods you’ll reach for most:

fn main() {
    let mut stack = vec![10, 20];
    stack.push(30);
    println!("after push: {stack:?}");

    let top = stack.pop();
    println!("pop gave {top:?}, left {stack:?}");

    println!("get(1) = {:?}", stack.get(1));
    println!("get(9) = {:?}", stack.get(9));
    println!("stack[1] = {}", stack[1]);

    let mut empty: Vec<i32> = Vec::new();
    println!("pop on empty: {:?}", empty.pop());
}

It prints:

after push: [10, 20, 30]
pop gave Some(30), left [10, 20]
get(1) = Some(20)
get(9) = None
stack[1] = 20
pop on empty: None
  • push adds an item at the end. pop removes the last one and returns it as an Option, because the vector might be empty.
  • get(i) returns Some(&item), or None if i is past the end.
  • v[i] returns the item itself, and panics if i is past the end.

So the choice between get and [] is a question: is a missing item a normal case, or a bug? If the index came from the user or from a search, use get and handle None. If your code made sure the index is valid, use []. On a two-item vector, v[2] stops the program with index out of bounds: the len is 2 but the index is 2, and that panic tells you your code was wrong.

A few more methods do jobs you’d otherwise write loops for:

fn main() {
    let mut tags = vec!["rust", "web", "cli", "rust", "async", "cli"];
    println!("has web? {}", tags.contains(&"web"));

    tags.sort();
    println!("sorted:   {tags:?}");
    tags.dedup();
    println!("deduped:  {tags:?}");

    tags.extend(["embedded", "wasm"]);
    println!("extended: {tags:?}");

    let first_two: Vec<&str> = tags.drain(..2).collect();
    println!("drained:  {first_two:?}");
    println!("left:     {tags:?}");
}

It prints:

has web? true
sorted:   ["async", "cli", "cli", "rust", "rust", "web"]
deduped:  ["async", "cli", "rust", "web"]
extended: ["async", "cli", "rust", "web", "embedded", "wasm"]
drained:  ["async", "cli"]
left:     ["rust", "web", "embedded", "wasm"]
  • contains takes a reference to the item, so we pass &"web". It checks every item in turn.
  • sort is stable: items that compare equal keep their order. sort_unstable doesn’t promise that, and in return it’s usually a little faster and needs no extra memory. For numbers and strings you can’t tell the difference.
  • dedup removes an item only when it equals the one right before it, so sort first.
  • extend appends every item from another collection.
  • drain(..2) removes a range of items and hands them to you. .collect() gathers them into a new Vec. Part 17 covers collect; for now, read it as “put these items into the collection named on the left”.

HashMap: values looked up by key

A HashMap<K, V> stores pairs: a key of type K and a value of type V. You look a value up by its key, not by its position. It lives in std::collections, so you use it first.

use std::collections::HashMap;

fn main() {
    let mut stock: HashMap<String, u32> = HashMap::new();
    stock.insert(String::from("apple"), 5);
    stock.insert(String::from("pear"), 2);

    let old = stock.insert(String::from("apple"), 8);
    println!("insert apple again, old value: {old:?}");

    println!("apple: {:?}", stock.get("apple"));
    println!("plum:  {:?}", stock.get("plum"));
    println!("has pear? {}", stock.contains_key("pear"));

    let removed = stock.remove("pear");
    println!("removed {removed:?}, {} left", stock.len());

    match stock.get("apple") {
        Some(n) => println!("we have {n} apples"),
        None => println!("no apples"),
    }
    let plums = stock.get("plum").copied().unwrap_or(0);
    println!("we have {plums} plums");
}

It prints:

insert apple again, old value: Some(5)
apple: Some(8)
plum:  None
has pear? true
removed Some(2), 1 left
we have 8 apples
we have 0 plums

Things to notice:

  • A key appears at most once. insert with a key that’s already there replaces the value and returns the old one, Some(5). For a new key it returns None.
  • The keys are String, but we look them up with "apple", a &str. A map with String keys accepts a &str for lookups.
  • remove returns the value it took out, as an Option.
  • get returns Option<&u32>. match handles both cases. The last line is the short form that fixes our first program: .copied() turns Option<&u32> into Option<u32>, and .unwrap_or(0) gives the number inside, or 0 for None.

Any type can be a value. A key needs two abilities: Rust must be able to compare two keys for equality, and to hash one. Strings, integers, char and bool have both. Part 14 shows how to give them to your own types with derive.

How a lookup finds the value

A Vec finds item 5 by jumping straight to position 5. A HashMap wants to jump straight to the right place too, but its keys are words, not positions. A hash function bridges the gap. It turns any key into a big number, and the same key always gives the same number. The map uses that number to pick a slot, called a bucket, in an array it keeps on the heap.

The animation shows two lookups in a small map with 8 buckets:

key hash key to number, % 8 bucket 5 "cat" "dog" buckets ant 4 cat 3 dog 7 0 1 2 3 4 5 6 7 key in bucket 5 is "cat": a match, value 3 key in bucket 5 is "cat", not "dog": try the next slot key in bucket 6 is "dog": a match, value 7 the map holds ant: 4, cat: 3, dog: 7 hash("cat") picks bucket 5 get("cat") returns Some(&3) collision: hash("dog") also picks bucket 5 get("dog") returns Some(&7) A HashMap with 8 buckets, 3 of them in use get("cat"): the hash function turns the key into a bucket number Go straight to bucket 5 and compare the keys: they match get("dog") lands on bucket 5 too, but the key there is "cat" Check the next slot: the key is "dog", so return its value

The hash of a key picks a bucket, so a lookup goes straight to the right place. The map still compares the stored key, because two different keys can land on the same bucket.

Here are those steps in words, in case the animation doesn’t play for you:

  1. The map has an array of 8 buckets on the heap. Three hold an entry: ant with 4 in bucket 1, cat with 3 in bucket 5, and dog with 7 in bucket 6.
  2. get("cat") runs the hash function on "cat". It gives a big number, and the map keeps only the part that fits the array (here, the remainder after dividing by 8). That picks bucket 5.
  3. The map goes straight to bucket 5. It doesn’t look at the other buckets. It compares the key stored there with "cat". They’re equal, so get returns Some(&3).
  4. get("dog") hashes to bucket 5 as well. Two keys landing on the same bucket is called a collision, and it’s normal. The key in bucket 5 is "cat", not "dog", so this isn’t the answer yet.
  5. When dog was inserted, its bucket was taken, so it went into the next free slot. The lookup follows the same path, finds "dog" in bucket 6, and returns Some(&7). If it had reached an empty slot first, it would have returned None.

That’s why a lookup stays fast however big the map gets: it usually checks one or two slots, not every entry. It’s also why keys must be hashable and comparable. The hash finds the neighbourhood, and the comparison confirms the key.

The picture is the idea, not the exact layout. Rust’s HashMap is a port of Google’s SwissTable design, which keeps a small tag byte per slot and checks a group of slots at once. The steps are the same: hash, jump, compare.

Iteration order is not something you can rely on

You can loop over a map with for (key, value) in &map. But in what order? The hash decides where each entry sits, so the order has nothing to do with the order you inserted them.

It’s worse than that. Rust’s default hash function is seeded with random keys, chosen fresh each time the program runs. This protects servers from an attack where someone sends many keys that all collide, which would make every lookup slow. The side effect is that the same program, with the same data, can list the keys in a different order on every run.

So this series never prints a HashMap directly. When the order matters, collect the keys into a Vec and sort them, as the word counter below does, or use a BTreeMap, which keeps its keys sorted.

The entry API: insert or update in one step

Counting things is the classic job for a map. For each word, if it’s new, start its count at 0. Then add 1. The entry method does both halves in one lookup:

use std::collections::HashMap;

fn main() {
    let text = "the cat sat on the mat the end";
    let mut counts = HashMap::new();
    for word in text.split_whitespace() {
        let n = counts.entry(word).or_insert(0);
        *n += 1;
    }

    let mut words: Vec<_> = counts.keys().collect();
    words.sort();
    for w in words {
        println!("{w}: {}", counts[w]);
    }
}

It prints:

cat: 1
end: 1
mat: 1
on: 1
sat: 1
the: 3

The last four lines are the sorting step from the section above. counts.keys() lists the keys, each as a reference, and Vec<_> tells collect to make a Vec and work out the item type itself. counts[w] reads a value and, like v[i], panics if the key is missing. Every w came from the map, so it can’t be.

counts.entry(word) finds the slot for word, whether or not anything is in it yet. .or_insert(0) puts 0 there if the slot was empty. Then it returns a &mut to the value, new or old. *n += 1 adds 1 through that reference. You’ll usually see it on one line: *counts.entry(word).or_insert(0) += 1;.

Without entry, you’d look the key up, and then look it up again to insert or to change it. That’s two lookups and more code.

Two more methods cover the other common shapes:

  • .or_default() inserts the type’s default value: 0 for numbers, an empty String, an empty Vec.
  • .and_modify(...) changes the value only if the key was already there. You chain .or_insert(...) after it for when it wasn’t. This is the one to use when the first value isn’t the same as “start at zero and update”.

Here both build two maps from a list of words: the words grouped by first letter, and the longest word for each letter:

use std::collections::HashMap;

fn main() {
    let words = ["apple", "banana", "avocado", "cherry", "blueberry", "fig"];

    let mut groups: HashMap<char, Vec<&str>> = HashMap::new();
    let mut longest: HashMap<char, &str> = HashMap::new();
    for w in words {
        let first = w.chars().next().unwrap();
        groups.entry(first).or_default().push(w);
        longest
            .entry(first)
            .and_modify(|best| {
                if w.len() > best.len() {
                    *best = w;
                }
            })
            .or_insert(w);
    }

    let mut letters: Vec<_> = groups.keys().collect();
    letters.sort();
    for c in letters {
        println!("{c}: {:?}, longest {}", groups[c], longest[c]);
    }
}

It prints:

a: ["apple", "avocado"], longest avocado
b: ["banana", "blueberry"], longest blueberry
c: ["cherry"], longest cherry
f: ["fig"], longest fig

w.chars().next() returns the first character as an Option, and .unwrap() takes it out. No word in the list is empty, so it’s safe here. groups.entry(first).or_default() gives a &mut Vec<&str>, an empty one the first time, and we push onto it.

The code inside and_modify(...) is a closure, a small function written inline. Part 16 covers closures; for now, read |best| { ... } as “given best, a &mut to the current value, run this code”. The first word for each letter goes in through or_insert(w). Every later word for that letter goes through and_modify, and replaces best only if it’s longer.

Who owns the keys and values

insert takes its key and value by value. If they’re Strings, they move into the map, the same as passing them to a function in Part 6:

use std::collections::HashMap;

fn main() {
    let mut pets = HashMap::new();
    let owner = String::from("Ana");
    let pet = String::from("Rex");
    pets.insert(owner, pet);
    println!("{owner} owns {}", pets["Ana"]);
}

It prints:

error[E0382]: borrow of moved value: `owner`
...
7 |     pets.insert(owner, pet);
  |                 ----- value moved here
8 |     println!("{owner} owns {}", pets["Ana"]);
  |                ^^^^^ value borrowed here after move
...
help: consider cloning the value if the performance cost is acceptable

The map owns the key and the value now, and drops them when it’s dropped. If you still need owner afterwards, clone it on the way in, as the help line says: pets.insert(owner.clone(), pet).

The other choice is a map of references, such as HashMap<&str, &str>. Then the map only borrows, and it can’t outlive the strings it points at (Part 9). Copy types like i32 are copied in, so there’s nothing to think about.

HashSet: just the keys

A HashSet<T> is a HashMap with keys and no values. It answers one question quickly: is this item in the set? Each item is stored once, so it’s also the easy way to remove duplicates.

use std::collections::HashSet;

fn main() {
    let visits = ["ana", "ben", "ana", "cai", "ben", "ana"];
    let mut seen = HashSet::new();
    for v in visits {
        if seen.insert(v) {
            println!("first visit: {v}");
        }
    }
    println!("{} different visitors", seen.len());
    println!("ben visited? {}", seen.contains("ben"));
}

It prints:

first visit: ana
first visit: ben
first visit: cai
3 different visitors
ben visited? true

insert returns true if the item was new and false if it was already there. contains uses the hash, so unlike Vec::contains it doesn’t check every item.

Sets also do set operations: what two sets share, what either one has, and what one has that the other doesn’t. Their results come out in hash order, so we sort them before printing:

use std::collections::HashSet;

fn main() {
    let monday = HashSet::from(["ana", "ben", "cai"]);
    let tuesday = HashSet::from(["ben", "cai", "dev"]);

    let mut both: Vec<_> = monday.intersection(&tuesday).collect();
    both.sort();
    let mut either: Vec<_> = monday.union(&tuesday).collect();
    either.sort();
    let mut only_monday: Vec<_> = monday.difference(&tuesday).collect();
    only_monday.sort();

    println!("both days:   {both:?}");
    println!("either day:  {either:?}");
    println!("monday only: {only_monday:?}");
}

It prints:

both days:   ["ben", "cai"]
either day:  ["ana", "ben", "cai", "dev"]
monday only: ["ana"]

HashSet::from([...]) builds a set from an array. HashMap::from takes an array of (key, value) pairs.

BTreeMap and BTreeSet: keys kept in order

A BTreeMap has nearly the same methods as a HashMap, including entry. The difference is inside: it keeps its keys sorted, in a tree of small sorted arrays called a B-tree. So it always lists its keys in order. Swap HashMap for BTreeMap in the word counter above, drop the sorting step, and println!("{counts:?}") prints {"cat": 1, "end": 1, "mat": 1, "on": 1, "sat": 1, "the": 3} on every run.

Because the keys are in order, a BTreeMap can also answer questions a HashMap can’t: which key is smallest, which is largest, and which keys fall in a range.

use std::collections::{BTreeMap, BTreeSet};

fn main() {
    let mut sales = BTreeMap::new();
    sales.insert(14, 120);
    sales.insert(3, 80);
    sales.insert(9, 95);
    sales.insert(21, 150);
    sales.insert(11, 60);

    println!("first: {:?}", sales.first_key_value());
    println!("last:  {:?}", sales.last_key_value());

    let mut week_two = 0;
    for (day, amount) in sales.range(8..15) {
        println!("day {day}: {amount}");
        week_two += amount;
    }
    println!("days 8 to 14 sold {week_two}");

    let tags = BTreeSet::from(["web", "cli", "rust", "cli"]);
    println!("{tags:?}");
}

It prints:

first: Some((3, 80))
last:  Some((21, 150))
day 9: 95
day 11: 60
day 14: 120
days 8 to 14 sold 275
{"cli", "rust", "web"}

The keys are days of the month and the values are sales. range(8..15) visits only the keys from 8 up to, but not including, 15, and it goes straight to 8 without walking past 3. BTreeSet is to BTreeMap what HashSet is to HashMap: sorted keys with no values. The duplicate "cli" was dropped.

The price is speed. A BTreeMap lookup walks down the tree, comparing keys as it goes, so it slows down a little as the map grows. For most programs both maps are fast enough. Keys in a BTreeMap must be ordered, comparable with <, rather than hashable.

VecDeque: a queue

A queue serves items in the order they arrived: add at the back, take from the front. A Vec is bad at the front. v.remove(0) takes out the first item and then shifts every other item down one place to close the gap. Empty a 100,000-item Vec that way, and it shifts about 5 billion items in total.

VecDeque (say “vec deck”, for double-ended queue) fixes that. Its buffer is a ring: it remembers where the front is, and taking the front item just moves that marker forward. Nothing shifts. When the back reaches the end of the buffer, it wraps round to the free space at the start.

use std::collections::VecDeque;

fn main() {
    let mut queue = VecDeque::new();
    queue.push_back("ana");
    queue.push_back("ben");
    queue.push_back("cai");
    queue.push_front("vip");
    println!("queue: {queue:?}");

    while let Some(next) = queue.pop_front() {
        println!("serving {next}, {} still waiting", queue.len());
    }
}

It prints:

queue: ["vip", "ana", "ben", "cai"]
serving vip, 3 still waiting
serving ana, 2 still waiting
serving ben, 1 still waiting
serving cai, 0 still waiting

push_front and pop_back work too, which is what “double-ended” means. while let is the loop form of if let from Part 11: it runs while pop_front returns Some, and stops at the first None.

Which collection to pick

You need Use Lookups Order when you loop
A list, read by position, added to at the end Vec by index, instant the order you added
Values looked up by a key HashMap by key, one or two slots none you can rely on
Values by key, in sorted order, or ranges BTreeMap by key, a walk down a tree sorted by key
“Have I seen this?” or no duplicates HashSet by item, one or two slots none you can rely on
Unique items, sorted BTreeSet by item, a walk down a tree sorted
A queue: in at the back, out at the front VecDeque by index, instant front to back

Start with Vec. Most lists are small, and checking every item of a 20-item Vec is quick. Move to a map or set when you look things up by value often, or the list gets large. The standard library also has BinaryHeap, which always hands you the largest item, and LinkedList, which is rarely the right answer.

Worked example: holding a value while the map changes

This is Part 8 again, in a map:

use std::collections::HashMap;

fn main() {
    let mut scores = HashMap::new();
    scores.insert("ana", 10);
    let ana = scores.get("ana");
    scores.insert("ben", 7);
    println!("ana has {ana:?}");
}

It prints:

error[E0502]: cannot borrow `scores` as mutable because it is also borrowed as immutable
 --> src/main.rs:7:5
  |
6 |     let ana = scores.get("ana");
  |               ------ immutable borrow occurs here
7 |     scores.insert("ben", 7);
  |     ^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
8 |     println!("ana has {ana:?}");
  |                        --- immutable borrow later used here

Read it from the top. Line 6: get returns Option<&i32>, a reference into the map, so scores is borrowed. Line 7: insert needs &mut scores. Line 8: the reference is still in use. Many readers or one writer, and here we asked for both.

The danger is real. When the bucket array gets too full, insert moves every entry to a bigger one, and ana would point into freed memory, just like the Vec buffer in Part 8. The fix: if the value is small and Copy, copy it out, so there’s no reference left to hold.

use std::collections::HashMap;

fn main() {
    let mut scores = HashMap::new();
    scores.insert("ana", 10);
    let ana = scores.get("ana").copied();
    scores.insert("ben", 7);
    println!("ana has {ana:?}");
}

It prints:

ana has Some(10)

For a String value, .cloned() does the same with a clone. Or move the lookup after the insert, so the borrow starts later.

Worked example: the most common words

Count the words in some text and list the most common ones, with ties in alphabetical order so the output is the same every run:

use std::cmp::Reverse;
use std::collections::HashMap;

fn main() {
    let text = "It was the best of times, it was the worst of times, \
                it was the age of wisdom, it was the age of foolishness";

    let mut counts: HashMap<String, u32> = HashMap::new();
    for raw in text.split_whitespace() {
        let word = raw.trim_end_matches(',').to_lowercase();
        *counts.entry(word).or_insert(0) += 1;
    }
    println!("{} different words", counts.len());

    let mut ranked = Vec::new();
    for (word, n) in &counts {
        ranked.push((Reverse(*n), word));
    }
    ranked.sort();
    for (Reverse(n), word) in &ranked[..6] {
        println!("{n} {word}");
    }
}

It prints:

10 different words
4 it
4 of
4 the
4 was
2 age
2 times

Step by step:

  • The \ at the end of a line inside a string joins it to the next line and skips the leading spaces.
  • to_lowercase makes It and it the same word. It returns a new String, so the map owns its keys.
  • A map can’t be sorted, so we copy its entries into a Vec of pairs. Each word is a &String borrowed from the map, so nothing is cloned.
  • Tuples sort by their first item, then by the second when the first items are equal. We want the biggest count first, so the count is wrapped in std::cmp::Reverse, which flips its order. Equal counts then sort by word.
  • &ranked[..6] is a slice of the first six pairs (Part 4), and the pattern (Reverse(n), word) takes each one apart.

Part 16 shows sort_by, which does this with a closure instead of Reverse.

Tips and traps

  • Printing a HashMap with {:?}. The order looks fixed when you test it, then changes on the next run, and a test that compares output fails now and then. Sort the keys first, or use a BTreeMap.
  • dedup left duplicates behind. It only removes an item equal to the one just before it. Call sort first, or use a HashSet if you need to keep the original order (Exercise 2).
  • sort on floats doesn’t compile. vec![2.5, 1.0].sort() fails with E0277, “the trait Ord is not implemented for {float}“, because NaN can’t be put in order. Use v.sort_by(f64::total_cmp), which gives every float, NaN included, a fixed place.
  • Vec::remove(0) in a loop. It works, and it gets slower as the list grows, because every removal shifts the rest. For a queue, use VecDeque and pop_front.
  • map[key] panics on a missing key with “no entry found for key”, and doesn’t say which key. Use get unless the key is certain to be there.
  • Vec::contains in a loop over a big list. It checks every item each time, so the program slows down fast as the list grows. Put the items in a HashSet once and call contains on that.

Pick the collection by the question you’ll ask it most: by position, by key, in order, or first in, first out.

Exercises

Exercise 1. Count how many times each letter appears in "mississippi", and print the counts in alphabetical order, one letter: count per line. Don’t write a sorting step.

Exercise 2. Remove the duplicates from ["ben", "ana", "ben", "cai", "ana", "dev"], but keep the names in the order they first appeared. The answer should be ["ben", "ana", "cai", "dev"]. Why doesn’t sort and dedup do this?

Exercise 3. Three jobs need work: a needs 3 turns, b needs 1 and c needs 2. Each turn, take the job at the front of a queue, do one unit of work on it, and put it at the back if it still needs more. Print work on <name> for every turn and <name> is done when a job finishes. Use a VecDeque of (name, turns left) pairs.

Answers

1. A BTreeMap keeps the letters sorted, so there’s nothing to sort. chars() walks the string one char at a time (Part 5).

use std::collections::BTreeMap;

fn main() {
    let mut counts = BTreeMap::new();
    for c in "mississippi".chars() {
        *counts.entry(c).or_insert(0) += 1;
    }
    for (c, n) in &counts {
        println!("{c}: {n}");
    }
}

It prints:

i: 4
m: 1
p: 2
s: 4

2. sort followed by dedup removes the duplicates, but it gives ["ana", "ben", "cai", "dev"]. The original order is lost. Instead, keep a HashSet of names you’ve seen, and push a name onto the result only when insert says it’s new:

use std::collections::HashSet;

fn main() {
    let names = ["ben", "ana", "ben", "cai", "ana", "dev"];

    let mut seen = HashSet::new();
    let mut unique = Vec::new();
    for name in names {
        if seen.insert(name) {
            unique.push(name);
        }
    }
    println!("{unique:?}");
}

It prints:

["ben", "ana", "cai", "dev"]

3. VecDeque::from builds the queue from an array. Each pass takes a pair off the front, and the pattern Some((name, left)) takes the pair apart.

use std::collections::VecDeque;

fn main() {
    let mut jobs = VecDeque::from([("a", 3), ("b", 1), ("c", 2)]);

    while let Some((name, left)) = jobs.pop_front() {
        println!("work on {name}");
        if left > 1 {
            jobs.push_back((name, left - 1));
        } else {
            println!("{name} is done");
        }
    }
}

It prints:

work on a
work on b
b is done
work on c
work on a
work on c
c is done
work on a
a is done

What’s next

A HashMap key must be hashable and comparable, and a BTreeMap key must be ordered. Those abilities are traits, and in Part 14 we’ll define our own traits, implement them, and use derive to get the common ones for free.

How useful was this post?

Click on a heart to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.