Rust Collections: Vec, String, HashMap
Store dynamic data on the heap using standard collection types in Rust: vectors for ordered lists, strings for UTF-8 text, and HashMaps for key-value pairs.
Ninth post in the basic Rust series. Unlike built-in arrays and tuples whose sizes are fixed at compile time, collections point to data allocated on the heap and can shrink or grow at runtime.
graph TD
subgraph Collections["Rust Standard Collections"]
Vec["Vec<T><br/>Dynamically sized ordered list"]
String["String<br/>UTF-8 encoded bytes wrapper"]
HashMap["HashMap<K, V><br/>Key-Value lookup table"]
end
subgraph Memory["Memory Layout"]
Stack["Stack: Pointer + Capacity + Length"]
Heap["Heap: Dynamic buffer allocation"]
end
Vec --> Stack
String --> Stack
HashMap --> Stack
Stack -->|points to| Heap
Vectors (Vec<T>)#
A vector stores multiple values of the same type sequentially in memory:
graph LR
subgraph StackMem["Stack Memory"]
V["vec"]
V_ptr["ptr"]
V_cap["cap: 4"]
V_len["len: 3"]
end
subgraph HeapMem["Heap Memory"]
H0["[0]: 10"]
H1["[1]: 20"]
H2["[2]: 30"]
H3["[3]: Unallocated"]
end
V_ptr --> H0
H0 --- H1 --- H2 --- H3
fn main() {
let mut v: Vec<i32> = Vec::new();
v.push(10);
v.push(20);
v.push(30);
// Using vec! macro
let v2 = vec![1, 2, 3];
// Accessing elements safely with get()
match v.get(1) {
Some(third) => println!("The second element is {third}"),
None => println!("There is no second element."),
}
// Iterating over values
for i in &v {
println!("{i}");
}
}rustUTF-8 Strings (String)#
In Rust, String is a wrapper over a Vec<u8> guaranteed to be valid UTF-8 text:
graph LR
subgraph StackFrame["Stack Frame"]
S["s (String)"]
S_ptr["ptr"]
S_cap["cap: 7"]
S_len["len: 7"]
end
subgraph HeapBuffer["Heap Buffer"]
B0["'f' (102)"]
B1["'o' (111)"]
B2["'o' (111)"]
B3["'b' (98)"]
B4["'a' (97)"]
B5["'r' (114)"]
B6["'!' (33)"]
end
S_ptr --> B0
B0 --- B1 --- B2 --- B3 --- B4 --- B5 --- B6
let mut s = String::from("foo");
s.push_str("bar");
s.push('!');
// Concatenation with + or format!
let s1 = String::from("Hello, ");
let s2 = String::from("world!");
let s3 = format!("{s1}{s2}"); // format! does not take ownershiprustBecause UTF-8 characters vary in byte length (1 to 4 bytes), Rust does not support direct indexing like s[0] to prevent returning invalid character bytes. Instead, use string slices &s[0..4] or iterate with .chars().
Hash Maps (HashMap<K, V>)#
A hash map maps keys of type K to values of type V using a hashing function:
graph LR
subgraph HashFunc["Hash Function"]
K1["Key: 'Blue'"] --> H1["Hash('Blue')"]
K2["Key: 'Yellow'"] --> H2["Hash('Yellow')"]
end
subgraph BucketArray["Bucket Array on Heap"]
H1 --> B1["Bucket 2: ('Blue', 10)"]
H2 --> B2["Bucket 5: ('Yellow', 50)"]
end
use std::collections::HashMap;
fn main() {
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);
// Accessing values
let team_name = String::from("Blue");
let score = scores.get(&team_name).copied().unwrap_or(0);
println!("Blue team score: {score}");
// Insert only if key is absent using entry API
scores.entry(String::from("Blue")).or_insert(25);
scores.entry(String::from("Red")).or_insert(100);
for (key, value) in &scores {
println!("{key}: {value}");
}
}rustConclusion#
Vectors store ordered element lists, Strings manage heap-allocated UTF-8 text safely, and HashMaps manage key-value associations. Next in this series: error handling.