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.
Vectors (Vec<T>)#
A vector stores multiple values of the same type sequentially in memory:
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:
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:
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.