Pick the collection for the operation.
Match membership, ordering, and queue behavior to the problem.
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.
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());
}{"Python", "Rust"}
next=Some("build")- 1
The set removes duplicates.
- 2
BTreeSet iteration is sorted.
- 3
pop_front implements the next FIFO operation.
cargo run -p lesson_sets_deques03 Mind the boundary
04 Your next build
Use a HashSet to deduplicate IDs and a VecDeque to process them in first-seen order.
Reveal one possible solution +
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
Which standard collection is a double-ended queue?
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.