Vectors & Collections
A Vec
Creating and growing a Vec
fn main() { let mut scores: Vec<i32> = Vec::new(); scores.push(88); scores.push(92); scores.push(79); println!("{:?}", scores); println!("First: {}", scores[0]); }
[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
fn main() { let scores = vec![88, 92, 79]; println!("{}", scores[10]); }
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:
fn main() { let scores = vec![88, 92, 79]; match scores.get(10) { Some(value) => println!("Found: {}", value), None => println!("No score at that index"), } }
No score at that index
Iterating with for
fn main() { let scores = vec![88, 92, 79]; let mut total = 0; for score in &scores { total += score; } println!("Total: {}", total); }
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
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"), } }
Priya is 30
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.