Skip to content
binshelf/ rust

Search lessons

Type a Rust, TypeScript or C# term, like Option, null or E0382.

    Compare Rust with

    Lessons

    Module 8 · Collections & strings

    8.1Vec, HashMap, HashSet & BTreeMap

    Rust's everyday collections next to the ones you already use, how the entry API counts and groups in one line, why indexing can panic, and which collection to pick.

    About 30 minutesBeginner

    On this page
    1. Concept map
    2. Vec<T>: the list you’ll use most
    3. HashMap<K, V> and the entry API
    4. HashSet<T>: unique values
    5. Sorted keys: BTreeMap<K, V>
    6. Changing a collection while you loop over it
    7. Which one should I use?
    8. Under the hood
    9. Common pitfalls
    10. Try it yourself

    Concept map

    Concept map: how your language and Rust handle each idea in this lesson
    ConceptTypeScriptC#Rust
    A growable listT[] (an array)List<T>Vec<T>
    Key-value lookupMap<K, V>Dictionary<TKey, TValue>HashMap<K, V>
    Unique valuesSet<T>HashSet<T>HashSet<T>
    Keys kept in sorted orderNone built in; sort the keys when you need themSortedDictionary<TKey, TValue>BTreeMap<K, V>
    Reading a missing index or keyundefinedThrows ArgumentOutOfRangeException or KeyNotFoundExceptionv[i] and map[&key] panic; .get() returns an Option
    Order of a hash map when you loop over itInsertion orderUnspecifiedUnspecified, and different on every run

    You already use a list, a map and a set every day. Rust has all three, under slightly different names, plus a sorted map that TypeScript doesn't have built inmatches C#'s SortedDictionary. They live in std::collections (except Vec, which is always in scope), they own their elements, and they follow the same borrowing rules as everything else. Three things will surprise you: reading a missing index can panic, a hash map’s order changes from run to run, and you can’t change a collection while you loop over it.

    Vec<T>: the list you’ll use most

    Vec<T> is Rust’s growable list: an arraya List<T> that owns its elements, stored next to each other in one heap buffer. Make one with vec![...], Vec::new() or .collect(). If you know roughly how many items are coming, Vec::with_capacity(n) allocates room for them up front, so the pushes don’t have to grow the buffer, like new List<int>(5). Arrays in TypeScript have no equivalent you’d use: new Array(5) makes five empty slots, not five slots of spare room.

    TypeScript
    squares.ts
    const squares: number[] = [];
    for (let n = 1; n <= 5; n++) {
      squares.push(n * n);
    }
    console.log(`[${squares.join(", ")}]`);
    console.log(`${squares.length} squares`);
    C#
    Squares.cs
    var squares = new List<int>(5);
    for (var n = 1; n <= 5; n++)
    {
        squares.Add(n * n);
    }
    Console.WriteLine($"[{string.Join(", ", squares)}]");
    Console.WriteLine($"{squares.Count} squares");
    Rust
    let mut squares = Vec::with_capacity(5); // room for 5, no regrowing
    for n in 1..=5 {
        squares.push(n * n);
    }
    println!("{squares:?}");
    println!("{} squares", squares.len());

    Output

    [1, 4, 9, 16, 25]
    5 squares

    Reading an element is where Rust differs. TypeScriptC# lets you write scores[10] and deals with a missing element its own way; Rust makes you say what should happen:

    TypeScript
    scores.ts
    function describe(scores: number[], index: number): string {
      const score = scores[index]; // number | undefined
      return score === undefined ? `no score ${index}` : `score ${index}: ${score}`;
    }
    
    const scores = [90, 85, 77];
    console.log(describe(scores, 2));
    console.log(describe(scores, 10));
    C#
    Scores.cs
    List<int> scores = [90, 85, 77];
    Console.WriteLine(Describe(scores, 2));
    Console.WriteLine(Describe(scores, 10));
    
    static string Describe(List<int> scores, int index) =>
        index < scores.Count ? $"score {index}: {scores[index]}" : $"no score {index}";
    Rust
    fn describe(scores: &[i32], index: usize) -> String {
        match scores.get(index) {
            Some(score) => format!("score {index}: {score}"),
            None => format!("no score {index}"),
        }
    }
    
    fn main() {
        let scores = vec![90, 85, 77];
        println!("{}", describe(&scores, 2));
        println!("{}", describe(&scores, 10));
    }

    Output

    score 2: 77
    no score 10

    Rust gives you two ways to read an element, and they differ in what happens when it isn’t there:

    • scores[10] returns the element itself and panics if the index is out of range, the way C# throws ArgumentOutOfRangeException, where TypeScript would quietly give you undefined. Use it when a wrong index is a bug.
    • scores.get(10) returns an Option<&i32>: Some(&value) or None. Use it when the index might be out of range and that’s a normal case. Option instead of null covers Option in depth.

    first() and last() work like get: they return an Option, because the Vec might be empty. Printed with {:?}, you see the Some; unwrap it with if let to get the value:

    let squares: Vec<i32> = (1..=5).map(|n| n * n).collect();
    println!("last {:?}", squares.last());
    if let Some(last) = squares.last() {
        println!("last {last}");
    }

    Output

    last Some(25)
    last 25

    HashMap<K, V> and the entry API

    HashMap is MapDictionary: keys to values, found by hashing the key. The classic first program is counting words. In TypeScript you read the old count, add one and set it back: two lookups.In C# you read the old count with GetValueOrDefault and write it back with the indexer: two lookups. Rust has a one-liner that looks the key up once:

    TypeScript
    wordCount.ts
    const text = "the cat saw the dog and the bird";
    const counts = new Map<string, number>();
    for (const word of text.split(" ")) {
      counts.set(word, (counts.get(word) ?? 0) + 1);
    }
    console.log(`${counts.size} distinct words`);
    console.log(`the: ${counts.get("the") ?? 0}`);
    C#
    WordCount.cs
    var text = "the cat saw the dog and the bird";
    var counts = new Dictionary<string, int>();
    foreach (var word in text.Split(' '))
    {
        counts[word] = counts.GetValueOrDefault(word) + 1;
    }
    Console.WriteLine($"{counts.Count} distinct words");
    Console.WriteLine($"the: {counts.GetValueOrDefault("the")}");
    Rust
    use std::collections::HashMap;
    
    let text = "the cat saw the dog and the bird";
    let mut counts: HashMap<&str, i32> = HashMap::new();
    for word in text.split(' ') {
        *counts.entry(word).or_insert(0) += 1;
    }
    println!("{} distinct words", counts.len());
    println!("the: {}", counts.get("the").copied().unwrap_or(0));

    Output

    6 distinct words
    the: 3

    Read *counts.entry(word).or_insert(0) += 1 from left to right:

    1. counts.entry(word) looks word up once and gives you an Entry: either occupied (the key is there) or vacant (it isn’t).
    2. .or_insert(0) inserts 0 if the entry was vacant. Either way, it returns a &mut i32: a mutable reference to the count that’s now inside the map.
    3. *… += 1 adds one through that reference. The * means “the value this reference points at”, as in Reading Rust’s symbols.
    The closest C# match is CollectionsMarshal.GetValueRefOrAddDefault(counts, word, out _)++, which also returns a reference into the dictionary. Rust’s version is the everyday way to do it, not an advanced API.

    The other Entry methods cover the usual cases:

    You want to…Write
    Insert a starting value, then change it*map.entry(key).or_insert(0) += 1
    Start from the type’s default (0, "", empty Vec)map.entry(key).or_default().push(item)
    Build the starting value only if it’s neededmap.entry(key).or_insert_with(|| expensive())
    Do one thing if it’s there, another if it isn’tmap.entry(key).and_modify(|n| *n += 1).or_insert(1)

    Everything else works much like MapDictionary, with Option where TypeScript returns undefinedC# throws or uses an out parameter:

    • map.insert(key, value) adds or replaces, and returns the old value as an Option.
    • map.get(&key) returns Option<&V>. map[&key] returns the value and panics if the key is missing.
    • map.remove(&key) returns the removed value as an Option. map.contains_key(&key) returns a bool.

    The keys in this example are &str slices of text, so the map borrows text and nothing is copied. If the map has to outlive the text, store owned keys instead: HashMap<String, i32>, inserting word.to_string(). You can still look those up with a plain &str: counts.get("the") works on a HashMap<String, i32>.

    HashSet<T>: unique values

    HashSet<T> is a HashMap with keys and no values, like TypeScript’s Set, like C#‘s HashSet<T>. insert returns true if the value was new and false if it was already there, exactly like HashSet<T>.Add, which saves the has check that TypeScript needs:

    TypeScript
    visitors.ts
    const visits = ["ada", "grace", "ada", "linus", "grace", "ada"];
    const seen = new Set<string>();
    for (const name of visits) {
      if (seen.has(name)) {
        console.log(`${name} again`);
      }
      seen.add(name);
    }
    console.log(`${seen.size} unique visitors`);
    console.log(`linus visited: ${seen.has("linus") ? "yes" : "no"}`);
    C#
    Visitors.cs
    string[] visits = ["ada", "grace", "ada", "linus", "grace", "ada"];
    var seen = new HashSet<string>();
    foreach (var name in visits)
    {
        if (!seen.Add(name))
        {
            Console.WriteLine($"{name} again");
        }
    }
    Console.WriteLine($"{seen.Count} unique visitors");
    Console.WriteLine($"linus visited: {(seen.Contains("linus") ? "yes" : "no")}");
    Rust
    use std::collections::HashSet;
    
    let visits = ["ada", "grace", "ada", "linus", "grace", "ada"];
    let mut seen = HashSet::new();
    for name in visits {
        if !seen.insert(name) {
            println!("{name} again");
        }
    }
    println!("{} unique visitors", seen.len());
    let visited = if seen.contains("linus") { "yes" } else { "no" };
    println!("linus visited: {visited}");

    Output

    ada again
    grace again
    ada again
    3 unique visitors
    linus visited: yes

    Set operations are methods that return iterators: a.intersection(&b), a.union(&b), a.difference(&b) (C#‘s IntersectWith and friends change the set in place instead) (TypeScript’s ES2025 Set methods of the same names return new sets). Their order is a hash set’s order, so sort the result before you print it.

    Sorted keys: BTreeMap<K, V>

    A HashMap has no useful order. When you loop over one, the entries come out in an order that depends on the hashes, and every HashMap hashes with its own random keys, so the order changes from run to run, and even two maps with the same contents in one run can differ. TypeScript’s Map remembers insertion order; Rust’s HashMap doesn’t.C#‘s Dictionary doesn’t promise an order either, but today it loops in insertion order until you remove an entry (later entries then reuse the freed slots), so code accidentally depends on it. Rust’s random order flushes that out on the first run.

    When you want the keys in order, use BTreeMap. It keeps them sorted, so looping over it gives you the smallest key first. It has the same lookup and insert methods as HashMap, including entry. Here it groups words by length:

    TypeScript
    byLength.ts
    const words = ["pear", "fig", "apple", "kiwi", "plum", "banana"];
    const byLength = new Map<number, string[]>();
    for (const word of words) {
      let group = byLength.get(word.length);
      if (group === undefined) {
        group = [];
        byLength.set(word.length, group);
      }
      group.push(word);
    }
    for (const length of [...byLength.keys()].sort((a, b) => a - b)) {
      console.log(`${length}: ${byLength.get(length)?.join(", ")}`);
    }
    C#
    ByLength.cs
    string[] words = ["pear", "fig", "apple", "kiwi", "plum", "banana"];
    var byLength = new SortedDictionary<int, List<string>>();
    foreach (var word in words)
    {
        if (!byLength.TryGetValue(word.Length, out var group))
        {
            group = [];
            byLength[word.Length] = group;
        }
        group.Add(word);
    }
    foreach (var (length, group) in byLength)
    {
        Console.WriteLine($"{length}: {string.Join(", ", group)}");
    }
    Rust
    use std::collections::BTreeMap;
    
    let words = ["pear", "fig", "apple", "kiwi", "plum", "banana"];
    let mut by_length: BTreeMap<usize, Vec<&str>> = BTreeMap::new();
    for word in words {
        by_length.entry(word.len()).or_default().push(word);
    }
    for (length, group) in &by_length {
        println!("{length}: {}", group.join(", "));
    }

    Output

    3: fig
    4: pear, kiwi, plum
    5: apple
    6: banana

    or_default() inserts an empty Vec the first time a length shows up, and push adds to whichever Vec is there. One line replaces the get, check, create and set steps. TypeScript’s Map.groupBy(words, (word) => word.length) does the grouping in one call too, but the groups come out in insertion order, so you’d still sort the keys.

    BTreeSet<T> is the sorted version of HashSet<T>, like SortedSet<T>. And when you need a queue, adding at one end and removing at the other, use VecDeque<T> (C#‘s Queue<T>) (TypeScript’s shift() on an array may move every remaining element; VecDeque doesn’t):

    use std::collections::VecDeque;
    
    let mut queue = VecDeque::from(["build", "test"]);
    queue.push_back("deploy");
    while let Some(job) = queue.pop_front() {
        println!("running {job}");
    }

    Output

    running build
    running test
    running deploy

    Changing a collection while you loop over it

    In TypeScript, pushing onto an array inside a for...of over it works, and the loop goes on to visit the new items too, which is an easy way to write an infinite loop.

    In C#, adding to a List<T> inside a foreach over it compiles, then throws at run time:

    Tasks.cs
    List<string> tasks = ["build", "test"];
    try
    {
        foreach (var task in tasks)
        {
            if (task == "build")
            {
                tasks.Add("deploy");
            }
        }
    }
    catch (InvalidOperationException error)
    {
        Console.WriteLine(error.Message);
    }

    Output

    Collection was modified; enumeration operation may not execute.

    Rust doesn’t compile it at all:

    let mut tasks = vec![String::from("build"), String::from("test")];
    for task in &tasks {
        if task == "build" {
            tasks.push(String::from("deploy"));
        }
    }

    Rust doesn't compile this: error E0502

    error[E0502]: cannot borrow `tasks` as mutable because it is also borrowed as immutable
     --> main.rs:4:9
      |
    2 | for task in &tasks {
      |             ------
      |             |
      |             immutable borrow occurs here
      |             immutable borrow later used here
    3 |     if task == "build" {
    4 |         tasks.push(String::from("deploy"));
      |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here

    for task in &tasks borrows tasks for the whole loop, and push needs a mutable borrow while that shared one is alive. That’s the many-readers-or-one-writer rule from References, and it isn’t fussiness: push can move the whole buffer to a bigger allocation (see Under the hood), which would leave task pointing at freed memory.

    The loop's borrow covers the push
    The loop's borrow covers the push. Each column is a value or a borrow; a mark means it's alive on that line.
    LineCodetasksowner&tasksshared borrow (&)pushmutable borrow (&mut)What happens
    1let mut tasks = vec![String::from("build"), String::from("test")];ownstasks starts
    2for task in &tasks {tasks alive&&tasks startsThe loop borrows tasks until it ends
    3 if task == "build" {tasks alive&tasks alive
    4 tasks.push(String::from("deploy"));tasks alive&tasks alive&mutpush startserrorError E0502: push needs &mut tasks while the loop's & is alive
    5 }tasks alive&tasks alive
    6}tasks ends&tasks ends

    Six lines of code. tasks owns the vector from line 1 to line 6. On line 2, for task in &tasks starts a shared borrow that stays alive until the loop ends on line 6. Line 4 calls tasks.push, which needs a mutable borrow while the shared one is still alive, so the compiler rejects it with error E0502.

    The fix is to decide first and change afterwards, so the two borrows don’t overlap. To remove items, retain keeps the ones you want in one pass, with no loop at all:

    TypeScript
    tasks.ts
    let tasks = ["build", "test"];
    if (tasks.includes("build")) {
      tasks.push("deploy");
    }
    console.log(tasks.join(", "));
    tasks = tasks.filter((task) => task !== "test");
    console.log(tasks.join(", "));
    C#
    Tasks.cs
    List<string> tasks = ["build", "test"];
    if (tasks.Contains("build"))
    {
        tasks.Add("deploy");
    }
    Console.WriteLine(string.Join(", ", tasks));
    tasks.RemoveAll(task => task == "test");
    Console.WriteLine(string.Join(", ", tasks));
    Rust
    let mut tasks = vec![String::from("build"), String::from("test")];
    if tasks.iter().any(|task| task == "build") {
        tasks.push(String::from("deploy"));
    }
    println!("{}", tasks.join(", "));
    tasks.retain(|task| task != "test");
    println!("{}", tasks.join(", "));

    Output

    build, test, deploy
    build, deploy

    The borrow that iter().any(...) takes ends when any returns, before push runs. If you need to add items based on every element, collect them into a second Vec first, then tasks.extend(new_items).

    Changing the elements themselves, without adding or removing any, is fine. Loop over &mut tasks (or call iter_mut()) and each item is a &mut you can write through, something a TypeScript for...of can’t do, something a C# foreach over a List<T> can’t do, because its loop variable is read-only. For maps, values_mut() does the same:

    let mut scores = vec![70, 85, 90];
    for score in &mut scores {
        *score += 5;
    }
    println!("{scores:?}");

    Output

    [75, 90, 95]

    Which one should I use?

    Ask these in order; the first “yes” gives you the collection:

    Which collection?
    1. Do you look values up by a key?

      Yes

      HashMap<K, V>Use BTreeMap<K, V> when you loop over it in key order, print it, or need a range of keys.

      No
    2. Do you only need to know whether a value is in the collection, with no duplicates?

      Yes

      HashSet<T>Use BTreeSet<T> when you want the values sorted.

      No
    3. Do you add or remove at both ends, like a queue?

      Yes

      VecDeque<T>push_back and pop_front are both fast.

      No
    4. Otherwise: A list of items in order: Vec<T>, the default.

    WhatWhenWhyHow
    Vec<T>A list in order: the default for almost everything.One contiguous buffer: fast to loop over, fast to index, cheap to push at the end.vec![1, 2, 3], Vec::with_capacity(n), .collect(). Read with .get(i) unless a bad index is a bug.
    VecDeque<T>A queue: add at one end, remove at the other.Removing from the front of a Vec shifts every element; a VecDeque doesn’t.push_back, pop_front.
    HashMap<K, V>Look-ups by key, counting, grouping, caching, when order doesn’t matter.Fast lookups on average, whatever the size.entry(key).or_insert(0) to count, .get(&key) to read. Keys need Eq and Hash.
    BTreeMap<K, V>Keys you want in sorted order: output, reports, ranges like “every key from 10 to 20”.Always sorted, so output is the same on every run. Lookups are a little slower than a HashMap.The same lookup and insert methods as HashMap, plus range(10..=20), first_key_value(). Keys need Ord.
    HashSet<T>Unique values, “have I seen this?”, membership tests.Fast contains and insert, and insert tells you if the value was new.if !seen.insert(x) { /* duplicate */ }.
    BTreeSet<T>Unique values you want sorted.Same as BTreeMap: sorted and deterministic.BTreeSet::from([3, 1, 2]) loops as 1, 2, 3.

    And for reading and changing what’s inside:

    WhatWhenWhyHow
    v[i], map[&key]The index or key is certainly there; a miss would be a bug.Short. A miss panics, which stops the bug early instead of hiding it.let first = scores[0];
    .get()The index or key might be missing, and that’s a normal case.Returns Option, so the compiler makes you handle “not there”.if let Some(score) = scores.get(i) { … }, .get(&key).copied().unwrap_or(0).
    .entry()Insert-or-update: counting, grouping, caching.One lookup, and no separate “is it there?” check.*counts.entry(word).or_insert(0) += 1.
    &mut v, values_mut()Change every element in place.No copy, and no indexes.for score in &mut scores { *score += 5; }
    retainRemove the elements that don’t match.One pass, in place, and no borrow conflict.tasks.retain(|task| task != "test").

    Rule of thumb: reach for Vec<T> first and HashMap<K, V> when you look things up by key. Switch to BTreeMap or BTreeSet as soon as you print or compare the order, because a hash map’s order changes from run to run. Read with .get() unless a miss is a bug, update maps with entry(), and decide what to change before you change it, never in the middle of a loop over the same collection.

    Under the hood

    A Vec<T> is the same three words as a String: a pointer to a heap buffer, a length (how many elements are in use) and a capacity (how many fit before it has to grow). When a push finds the buffer full, the Vec allocates a bigger one, copies the elements across and frees the old one. Here’s that moment:

    let mut scores: Vec<i32> = Vec::with_capacity(4);
    scores.extend([10, 20, 30, 40]);
    scores.push(50); // full: allocate a bigger buffer, copy, free the old one
    println!("len {}, capacity {}", scores.len(), scores.capacity());

    Output

    len 5, capacity 8
    After scores.push(50) on a full VecOn the stack, scores is a Vec of i32 with a pointer, a length of 5 and a capacity of 8. Before the push, its buffer held 10, 20, 30 and 40 with no room left. The push allocated a new buffer with 8 slots, copied the four values, added 50, and freed the old buffer. The pointer now leads to the new buffer: 5 slots in use and 3 spare. Anything that pointed into the old buffer would now point at freed memory.StackHeapscores: Vec<i32>ptrlen5capacity8old buffer: freed10203040new buffer: 5 used, 3 spare1020304050
    After scores.push(50) on a full Vec. On the stack, scores is a Vec of i32 with a pointer, a length of 5 and a capacity of 8. Before the push, its buffer held 10, 20, 30 and 40 with no room left. The push allocated a new buffer with 8 slots, copied the four values, added 50, and freed the old buffer. The pointer now leads to the new buffer: 5 slots in use and 3 spare. Anything that pointed into the old buffer would now point at freed memory.

    That move is why Rust won’t let you push while a reference into the Vec is alive, and why with_capacity helps when you know the size: no regrowing, no copying. The capacity roughly doubles each time it grows, so a long run of push calls is still cheap on average. The exact numbers are an implementation detail; today, starting from empty, a Vec<i32> grows like this:

    let mut scores = Vec::new();
    println!("capacity {}", scores.capacity());
    let mut capacity = scores.capacity();
    for score in 1..=9 {
        scores.push(score);
        if scores.capacity() != capacity {
            capacity = scores.capacity();
            println!("len {}: capacity {capacity}", scores.len());
        }
    }

    Output

    capacity 0
    len 1: capacity 4
    len 5: capacity 8
    len 9: capacity 16

    Vec::new() doesn’t allocate at all; the first push does. An arrayA List<T> works the same way inside: C#‘s List<T> is also a buffer plus a count, and Capacity is right there to read.a JavaScript engine also keeps spare room behind an array, but it doesn’t show you.

    HashMap stores its entries in one table, placed by the key’s hash. By default it hashes with random keys, so an attacker can’t send keys that all land in the same slot and slow your server down (a “hash flooding” attack). Each thread seeds its keys from the operating system once, and each new map gets keys different from the last, which is why the order changes between runs and between maps. The algorithm today is SipHash 1-3, but the standard library doesn’t promise that and may change it. Keys need Eq and Hash, which you get with #[derive(PartialEq, Eq, Hash)] on your own types; Standard traits covers derives.

    BTreeMap keeps its entries in a B-tree: sorted, with several keys per tree node so lookups touch few allocations. Lookups and inserts take time proportional to the log of the size instead of constant time on average, which you’ll rarely notice. Keys need Ord, so the map can compare them.

    Common pitfalls

    Common pitfallA hash map prints in a different order every run

    println!("{counts:?}") on a HashMap prints the entries in hash order, and that order can change every time the program runs. Tests that compare the output pass once and fail the next time. Sort the entries first, or use a BTreeMap:

    use std::collections::HashMap;
    
    let counts = HashMap::from([("pear", 2), ("fig", 5), ("apple", 1)]);
    let mut pairs: Vec<(&str, i32)> = counts.into_iter().collect();
    pairs.sort();
    println!("{pairs:?}");

    Output

    [("apple", 1), ("fig", 5), ("pear", 2)]

    Common pitfallget gives you a reference, not the value

    counts.get("the") returns Option<&i32>, a borrow of the value inside the map, so a plain number doesn’t fit as its fallback:

    use std::collections::HashMap;
    
    let mut counts: HashMap<&str, i32> = HashMap::new();
    counts.insert("the", 3);
    let the: i32 = counts.get("the").unwrap_or(0);

    Rust doesn't compile this: error E0308

    error[E0308]: mismatched types
     --> main.rs:5:44
      |
    5 | let the: i32 = counts.get("the").unwrap_or(0);
      |                                  --------- ^ expected `&i32`, found integer
      |                                  |
      |                                  arguments to this method are incorrect
      |
    help: the return type of this call is `{integer}` due to the type of the argument passed
     --> main.rs:5:16
      |
    5 | let the: i32 = counts.get("the").unwrap_or(0);
      |                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^-^
      |                                            |
      |                                            this argument influences the return type of `unwrap_or`
    note: method defined here
    help: consider borrowing here
      |
    5 | let the: i32 = counts.get("the").unwrap_or(&0);
      |                                            +
    
    error[E0308]: mismatched types
     --> main.rs:5:16
      |
    5 | let the: i32 = counts.get("the").unwrap_or(0);
      |          ---   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `i32`, found `&i32`
      |          |
      |          expected due to this
      |
    help: consider dereferencing the borrow
      |
    5 | let the: i32 = *counts.get("the").unwrap_or(0);
      |                +

    For Copy values like numbers, add .copied() to turn Option<&i32> into Option<i32>: counts.get("the").copied().unwrap_or(0). For other values, keep the reference, or .cloned() if you really need your own copy.

    Common pitfallFloating-point numbers can't be keys

    f64 doesn’t implement Eq or Hash, because NaN isn’t equal to itself, so a HashMap or HashSet keyed by f64 has no insert:

    use std::collections::HashMap;
    
    let mut prices: HashMap<f64, &str> = HashMap::new();
    prices.insert(9.99, "book");

    Rust doesn't compile this: error E0599

    error[E0599]: the method `insert` exists for struct `HashMap<f64, &str>`, but its trait bounds were not satisfied
     --> main.rs:4:8
      |
    4 | prices.insert(9.99, "book");
      |        ^^^^^^
      |
      = note: the following trait bounds were not satisfied:
              `f64: Eq`
              `f64: Hash`

    Use a whole-number key instead, such as the price in cents as a u64.

    Try it yourself

    Exercise: port this to Rust

    Port this program to Rust. Add up each customer’s orders and print the totals in alphabetical order, then the number of customers.

    Starting code in TypeScript
    totals.ts
    const orders: [string, number][] = [
      ["linus", 12],
      ["ada", 30],
      ["grace", 40],
      ["ada", 15],
      ["linus", 8],
    ];
    const totals = new Map<string, number>();
    for (const [customer, amount] of orders) {
      totals.set(customer, (totals.get(customer) ?? 0) + amount);
    }
    for (const customer of [...totals.keys()].sort()) {
      console.log(`${customer}: ${totals.get(customer)}`);
    }
    console.log(`${totals.size} customers`);
    Starting code in C#
    Totals.cs
    (string Customer, int Amount)[] orders =
    [
        ("linus", 12),
        ("ada", 30),
        ("grace", 40),
        ("ada", 15),
        ("linus", 8),
    ];
    var totals = new SortedDictionary<string, int>(StringComparer.Ordinal);
    foreach (var (customer, amount) in orders)
    {
        totals[customer] = totals.GetValueOrDefault(customer) + amount;
    }
    foreach (var (customer, total) in totals)
    {
        Console.WriteLine($"{customer}: {total}");
    }
    Console.WriteLine($"{totals.Count} customers");

    Expected output

    ada: 45
    grace: 40
    linus: 20
    3 customers
    Show a hint

    Use a BTreeMap<&str, u32> so the customers come out in alphabetical order without sorting. Add each amount with *totals.entry(customer).or_insert(0) += amount, then loop over &totals.

    Show a solution
    use std::collections::BTreeMap;
    
    fn main() {
        let orders = [
            ("linus", 12),
            ("ada", 30),
            ("grace", 40),
            ("ada", 15),
            ("linus", 8),
        ];
        let mut totals: BTreeMap<&str, u32> = BTreeMap::new();
        for (customer, amount) in orders {
            *totals.entry(customer).or_insert(0) += amount;
        }
        for (customer, total) in &totals {
            println!("{customer}: {total}");
        }
        println!("{} customers", totals.len());
    }

    entry finds or creates each customer's total in one lookup, and the BTreeMap keeps the names sorted, so the output is the same on every run. A HashMap would need its entries collected and sorted before printing.

    Saved in this browser only.