Vec & HashMap in Rust

From the Rust cheat sheet ยท Collections & Iterators ยท verified Jul 2026

Vec & HashMap

Dynamic arrays and key-value maps.

rust
// Vec โ€” dynamic array
let mut v = vec![1, 2, 3];
v.push(4);
v.pop();              // Some(4)
let first = &v[0];   // Panics if out of bounds
let first = v.get(0); // Returns Option<&T>

// HashMap
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert("Alice", 30);
map.get("Alice");     // Some(&30)
๐Ÿ’ก Use v.get(i) instead of v[i] to avoid panics โ€” returns Option<&T>
โšก The entry().or_insert() pattern is the idiomatic way to insert-if-absent in HashMaps
๐Ÿ“Œ .collect() can build Vec, HashMap, String, and more โ€” the target type determines behavior
๐ŸŸข Use &v to borrow during iteration, v to consume, &mut v to mutate in place
vechashmapcollections

More Rust tasks

Back to the full Rust cheat sheet