Vectors & Collections

A Vec is Rust's growable array — a fixed-size array's more flexible sibling — and it's the collection you'll reach for by default any time you need a list of things whose length isn't known up front.

Creating and growing a Vec

Rust src/main.rs
fn main() {
    let mut scores: Vec<i32> = Vec::new();
    scores.push(88);
    scores.push(92);
    scores.push(79);

    println!("{:?}", scores);
    println!("First: {}", scores[0]);
}
Output
[88, 92, 79]
First: 88

Vec::new() starts empty; .push() appends. {:?} inside a format string is the "debug" formatter — it works on most built-in types and is the easy way to print a whole collection at once. The macro shorthand vec![88, 92, 79] builds one pre-filled in a single line, which you'll see used constantly in real Rust code.

Indexing panics; .get() doesn't

Rust src/main.rs
fn main() {
    let scores = vec![88, 92, 79];
    println!("{}", scores[10]);
}
Output (cargo run)
thread 'main' panicked at src/main.rs:3:24:
index out of bounds: the len is 3 but the index is 10

Square-bracket indexing panics immediately if the index is out of range — the program crashes right there, on the spot. .get() is the safer alternative: it returns an Option<&T> instead, so a missing index becomes a value you can check rather than a crash:

Rust src/main.rs
fn main() {
    let scores = vec![88, 92, 79];

    match scores.get(10) {
        Some(value) => println!("Found: {}", value),
        None => println!("No score at that index"),
    }
}
Output
No score at that index

Iterating with for

Rust src/main.rs
fn main() {
    let scores = vec![88, 92, 79];
    let mut total = 0;

    for score in &scores {
        total += score;
    }
    println!("Total: {}", total);
}
Output
Total: 259

Note &scores in the loop — iterating by reference borrows each element instead of moving the whole vector into the loop, so scores is still usable afterward. Leaving off the & would move (and thereby consume) the vector.

HashMap for key-value data

Rust src/main.rs
use std::collections::HashMap;

fn main() {
    let mut ages: HashMap<String, i32> = HashMap::new();
    ages.insert(String::from("Priya"), 30);
    ages.insert(String::from("Sam"), 25);

    match ages.get("Priya") {
        Some(age) => println!("Priya is {}", age),
        None => println!("Not found"),
    }
}
Output
Priya is 30
Note: HashMap::get returns an Option for exactly the same reason Vec::get does — a missing key is an entirely normal thing to check for, not something that should crash your program. You'll use this Option/match pairing everywhere in idiomatic Rust; the next lesson covers it properly.