Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ COLLECTIONS THAT WORK
BUILD NOTE 23 / 53

Pick the collection for the operation.

Match membership, ordering, and queue behavior to the problem.

BY NAVAN SAMI◷ 7 MIN READFOUNDATIONSRUST 2024

01 Understand the contract

HashSet keeps unique values and supports membership operations. BTreeMap and BTreeSet maintain sorted key order and logarithmic tree operations. VecDeque provides efficient insertion and removal at both ends, making it a natural FIFO queue. A collection choice is an operational contract: think about lookup, insertion, ordering, and how you will iterate. Avoid introducing a hash table just because it is familiar when a short vector or sorted map expresses the work more clearly.

02 Make it concrete

This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.

lessons/sets-deques/src/main.rs
use std::collections::{BTreeSet, VecDeque};
fn main() {
    let names: BTreeSet<_> = ["Rust", "Python", "Rust"].into_iter().collect();
    let mut queue = VecDeque::from(["build", "test"]);
    queue.push_back("ship");
    println!("{names:?}");
    println!("next={:?}", queue.pop_front());
}
↳ EXPECTED OUTPUT
{"Python", "Rust"}
next=Some("build")
  1. 1

    The set removes duplicates.

  2. 2

    BTreeSet iteration is sorted.

  3. 3

    pop_front implements the next FIFO operation.

From the extracted rust-workbench folder
cargo run -p lesson_sets_deques

03 Mind the boundary

04 Your next build

A SMALL MISSION

Use a HashSet to deduplicate IDs and a VecDeque to process them in first-seen order.

Reveal one possible solution +
solutions/sets-deques/src/main.rs
use std::collections::{HashSet, VecDeque};
fn main() {
    let mut seen = HashSet::new();
    let mut work = VecDeque::new();
    for id in [3, 1, 3, 2] {
        if seen.insert(id) {
            work.push_back(id);
        }
    }
    assert_eq!(work.into_iter().collect::<Vec<_>>(), [3, 1, 2]);
}

05 Check your reasoning

QUICK SIGNAL CHECK

Which standard collection is a double-ended queue?

ONE MORE CONTRACT YOU CAN EXPLAIN.

Understand it.
Then make it yours.

Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.