Quick Ref: Collections ​
Updated Mar 2026Collection Comparison ​
Vec<T> ​
rust
// Creation
let mut v: Vec<i32> = Vec::new();
let v2 = vec![1, 2, 3];
let v3 = vec![0; 10]; // [0, 0, 0, ..., 0]
// Adding
v.push(1);
v.push(2);
v.extend([3, 4, 5]);
v.insert(0, 0); // Insert at index
// Accessing
let third = &v[2]; // Panics if out of bounds
let third = v.get(2); // Returns Option<&T>
// Removing
let last = v.pop(); // Returns Option<T>
let removed = v.remove(0); // Remove at index, shifts elements
v.retain(|&x| x % 2 == 0); // Keep only even numbers
v.clear();
// Iterating
for item in &v { } // Borrow
for item in &mut v { } // Mutable borrow
for item in v { } // Consuming (v is gone)
// Useful methods
v.len();
v.is_empty();
v.contains(&42);
v.sort();
v.sort_by(|a, b| b.cmp(a)); // Reverse sort
v.dedup(); // Remove consecutive duplicates (sort first!)
v.iter().enumerate();
v.chunks(3); // Iterate in chunks
v.windows(2); // Sliding windowString ​
rust
// Creation
let s = String::new();
let s = String::from("hello");
let s = "hello".to_string();
let s = format!("{} {}", "hello", "world");
// Appending
let mut s = String::from("hello");
s.push(' '); // Single char
s.push_str("world"); // String slice
s += " !"; // Add assign
// Concatenation
let s1 = String::from("Hello, ");
let s2 = String::from("world!");
let s3 = s1 + &s2; // s1 is moved! s2 is borrowed
let s4 = format!("{s3} {s2}"); // Neither moved
// Iteration (no indexing!)
for c in "hello".chars() { } // By character
for b in "hello".bytes() { } // By byte
for (i, c) in "hello".char_indices() { }
// Slicing (must be at char boundaries!)
let hello = &s[0..5]; // Works for ASCII
// let broken = &s[0..1]; // PANICS if first char is multi-byte!
// Useful methods
s.len(); // Byte count (NOT char count!)
s.chars().count(); // Character count
s.contains("llo");
s.starts_with("he");
s.ends_with("lo");
s.trim();
s.replace("hello", "hi");
s.split_whitespace();
s.split(',');
s.to_uppercase();
s.to_lowercase();
s.is_empty();HashMap<K, V> ​
rust
use std::collections::HashMap;
// Creation
let mut scores: HashMap<String, i32> = HashMap::new();
let scores: HashMap<_, _> = vec![("Blue", 10), ("Red", 50)]
.into_iter()
.collect();
// Insert
scores.insert("Blue".to_string(), 10);
scores.insert("Red".to_string(), 50);
// Access
let blue = scores.get("Blue"); // Option<&V>
let blue = scores["Blue"]; // Panics if missing
// Update
scores.insert("Blue".to_string(), 25); // Overwrite
// Insert only if missing
scores.entry("Yellow".to_string()).or_insert(30);
// Modify existing
let count = scores.entry("Blue".to_string()).or_insert(0);
*count += 10;
// Word frequency pattern
let text = "hello world hello rust";
let mut word_count: HashMap<&str, u32> = HashMap::new();
for word in text.split_whitespace() {
*word_count.entry(word).or_insert(0) += 1;
}
// Iterate
for (key, value) in &scores {
println!("{key}: {value}");
}
// Remove
scores.remove("Blue");
// Useful methods
scores.len();
scores.is_empty();
scores.contains_key("Blue");
scores.keys();
scores.values();
scores.iter();
scores.retain(|_, v| *v > 20);HashSet<T> ​
rust
use std::collections::HashSet;
let mut set: HashSet<i32> = HashSet::new();
set.insert(1);
set.insert(2);
set.insert(3);
set.insert(2); // Duplicate — ignored
assert_eq!(set.len(), 3);
let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
let b: HashSet<_> = [3, 4, 5].iter().cloned().collect();
// Set operations
let union: HashSet<_> = a.union(&b).collect(); // {1,2,3,4,5}
let intersection: HashSet<_> = a.intersection(&b).collect(); // {3}
let difference: HashSet<_> = a.difference(&b).collect(); // {1,2}
let symmetric: HashSet<_> = a.symmetric_difference(&b).collect(); // {1,2,4,5}
set.contains(&1);
set.is_subset(&a);
set.is_superset(&a);VecDeque<T> ​
rust
use std::collections::VecDeque;
let mut deque = VecDeque::new();
deque.push_back(1); // [1]
deque.push_back(2); // [1, 2]
deque.push_front(0); // [0, 1, 2]
let front = deque.pop_front(); // Some(0), deque = [1, 2]
let back = deque.pop_back(); // Some(2), deque = [1]BTreeMap<K, V> and BTreeSet<T> ​
rust
use std::collections::BTreeMap;
let mut map = BTreeMap::new();
map.insert("banana", 3);
map.insert("apple", 5);
map.insert("cherry", 1);
// Iteration is sorted by key!
for (k, v) in &map {
println!("{k}: {v}");
}
// Output: apple: 5, banana: 3, cherry: 1
// Range queries
for (k, v) in map.range("banana"..) {
println!("{k}: {v}");
}Performance Comparison ​
| Operation | Vec | HashMap | BTreeMap | VecDeque |
|---|---|---|---|---|
| Index access | O(1) | O(1) avg | O(log n) | O(1) |
| Search | O(n) | O(1) avg | O(log n) | O(n) |
| Insert end | O(1)* | O(1) avg | O(log n) | O(1)* |
| Insert front | O(n) | N/A | O(log n) | O(1)* |
| Remove | O(n) | O(1) avg | O(log n) | O(n) |
| Sorted iteration | O(n log n) | No | O(n) | O(n log n) |
*amortized