Collections: Vector, String, and HashMap
Store groups of values with Rust’s common collection types.
Learning objectives
- Use Vec for dynamic lists
- Work with String values
- Store key-value pairs with HashMap
Vector
A Vec stores a growable list of values of the same type. It is one of the most common collection types in Rust.
String
String is a growable, owned text type. It is different from string slices and is useful when you need to modify text.
HashMap
A HashMap stores key-value pairs. It is useful for lookups such as scores, settings, and product quantities.
Example code
use std::collections::HashMap;
fn main() {
let mut scores = vec![80, 90, 75];
scores.push(88);
let mut message = String::from("Hello");
message.push_str(", Rust");
let mut marks = HashMap::new();
marks.insert("Alice", 90);
marks.insert("Ben", 85);
println!("{:?}", scores);
println!("{}", message);
println!("Alice: {:?}", marks.get("Alice"));
}
Practice task: Create a HashMap that stores three product names and their prices, then print one selected price.