GGistDev

Collections in Rust

Rust’s standard library provides growable collections: Vec, String, HashMap, HashSet, and more.

Vec (growable array)

let mut v = Vec::new();
v.push(1);
let v2 = vec![1,2,3];
for x in &v2 { println!("{x}"); }
if let Some(last) = v2.last() { println!("{last}"); }

Slicing borrows portions without copying: &v2[1..].

String and &str

Owned UTF‑8 buffer vs borrowed string slice.

let mut s = String::from("hi");
s.push('!');
let r: &str = &s;

HashMap

Key/value store with hashing; requires Eq and Hash on keys.

use std::collections::HashMap;
let mut m = HashMap::new();
m.insert("a", 1);
if let Some(v) = m.get("a") { println!("{v}"); }
for (k, v) in &m { println!("{k}={v}"); }

Entry API for upsert patterns:

m.entry("count").and_modify(|c| *c += 1).or_insert(0);

Iterators and adapters

Collections expose iterators (iter, iter_mut, into_iter) and rich adapters (map, filter, collect).

let squares: Vec<_> = (0..5).map(|n| n*n).collect();

Capacity and performance

Reserve capacity to avoid reallocations: v.reserve(100).

Summary

  • Use Vec/String for growable buffers; borrow with slices/&str
  • Use HashMap with entry API for updates; iterate with adapters and collect