Collections in Rust
Rust provides a variety of collection types for storing and managing related data. Collections are fundamental for handling multiple values in your programs.
Vectors
Vectors store sequences of values. They are growable and can hold multiple items of the same type:
fn main() { let mut numbers = vec![1, 2, 3]; numbers.push(4); for n in numbers.iter() { println!("{}", n); } }
Strings
Rust strings are UTF-8 encoded. They are growable and support efficient concatenation:
fn main() { let mut s = String::from("Rust"); s.push_str(" is fun"); println!("{}", s); }
Hash Maps
Hash maps store key-value pairs where both keys and values can be of different types:
use std::collections::HashMap; fn main() { let mut scores = HashMap::new(); scores.insert(String::from("Alice"), 100); scores.insert(String::from("Bob"), 85); for (key, value) in &scores { println!("{}: {}", key, value); } }
Tuples
Tuples are fixed-size collections of values of different types:
fn main() { let person = ("John", 30, true); println!("{} is {} years old and {}", person.0, person.1, person.2); }
Arrays
Arrays have a fixed size and can store values of the same type:
fn main() { let months = ["January", "February", "March", "April", "May", "June"]; println!("First month: {}", months[0]); }
Memory Management
Rust collections handle their memory automatically. When a collection goes out of scope, it is dropped, and the memory is freed.
fn main() { let v = vec![1, 2, 3]; // v owns the data } // v goes out of scope here, memory freed
Iterators
Iterators are used to perform actions on each item in the collection:
fn main() { let numbers = vec![1, 2, 3, 4, 5]; let doubled: Vec<_> = numbers.iter().map(|x| x * 2).collect(); println!("Doubled numbers: {:?}", doubled); }