Skip to content

02. Standard Library Collections

Rust’s standard library provides several powerful collections that are allocated on the heap.

1. Vectors (Vec<T>)

Vectors are dynamic arrays that can grow or shrink in size.

let mut v = Vec::new();
v.push(1);
v.push(2);

// Initialization with a macro
let v2 = vec![1, 2, 3, 4, 5];

// Reading elements
let third: &i32 = &v2[2]; // Can panic if out of bounds!
let third_safe: Option<&i32> = v2.get(2); // Safer: returns an Option

2. Strings

In Rust, there are two main string types: String (owned, growable) and &str (a string slice).

let mut s = String::from("hello");
s.push_str(" world"); // Concatenate strings

// Indexing into strings is not allowed because of UTF-8 complexity.
// Use slices or iterators instead.
for c in "नमस्ते".chars() {
    println!("{}", c);
}

3. HashMaps (HashMap<K, V>)

HashMaps store data in key-value pairs.

use std::collections::HashMap;

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); // Returns Option<&V>

// Iterating
for (key, value) in &scores {
    println!("{}: {}", key, value);
}

Entry API

The entry API allows you to conditionally insert values only if a key doesn’t exist.

scores.entry(String::from("Blue")).or_insert(25);

Collections lead us to Module 03, where we learn how to handle situations where things might go wrong.