Rust Tutorial · Structs, Enums and Collections · Lesson 16 of 29
Rust Collections: Vec, HashMap and More
Store lists in Vec, key-value data in HashMap and BTreeMap, and unique values in HashSet.
Vec
fn main() {
let mut prices = vec![8.5, 24.0, 31.9];
prices.push(5.0);
prices.sort_by(|a, b| a.partial_cmp(b).unwrap());
println!("{prices:?}");
println!("cheapest: {}, len: {}", prices[0], prices.len());
if let Some(last) = prices.last() {
println!("most expensive: {last}");
}
prices.retain(|&p| p < 30.0);
println!("under 30: {prices:?}");
}
Output
[5.0, 8.5, 24.0, 31.9] cheapest: 5, len: 4 most expensive: 31.9 under 30: [5.0, 8.5, 24.0]
Run this on your computer — see “Get Started” for setup.
HashMap and BTreeMap
HashMap is the general-purpose map (iteration order is unspecified); BTreeMap keeps keys sorted. The
entry API updates or inserts in one step:
use std::collections::{BTreeMap, HashSet};
fn main() {
let text = "the cat and the dog and the bird";
let mut counts: BTreeMap<&str, u32> = BTreeMap::new();
for word in text.split_whitespace() {
*counts.entry(word).or_insert(0) += 1;
}
println!("{counts:?}");
let unique: HashSet<&str> = text.split_whitespace().collect();
println!("{} unique words", unique.len());
}
Output
{"and": 2, "bird": 1, "cat": 1, "dog": 1, "the": 3}
5 unique wordsRun this on your computer — see “Get Started” for setup.
HashSet/BTreeSet store unique values, and VecDeque is a double-ended queue.
Test yourself
When would you choose BTreeMap over HashMap?
For faster lookupsWhen you need keys kept in sorted orderFor string keys onlyWhen values are numbers
Show answer
Answer: When you need keys kept in sorted order