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.

Create a free account to save this page, take notes and track your progress. Sign in

Vec

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:

Counting with the entry API
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 words

Run 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?

  1. For faster lookups
  2. When you need keys kept in sorted order
  3. For string keys only
  4. When values are numbers
Show answer

Answer: When you need keys kept in sorted order

Was this page helpful?