Vectors (Vec)
Flexible lists: push, len, index, iter().sum() and printing with {:?}.
Simple enough for a 5-year-old to understand
Create and append to a Vec
fn main() { let mut v = vec![1, 2]; v.push(3); println!("{:?}", v);}Flexible lists: push, len, index, iter().sum() and printing with {:?}.
Simple enough for a 5-year-old to understand
fn main() { let mut v = vec![1, 2]; v.push(3); println!("{:?}", v);}Vec is Rust's growable array and the most commonly used collection. It stores elements contiguously in memory, manages its own size, and frees its memory when it goes out of scope. It corresponds to C++'s vector type.
The safety guarantee Rust adds is bounds checking. If you go out of bounds with index access, the program STOPS with a clean message; unlike in C, it does not read neighboring memory. If you don't want it to stop, the get method reports the presence of a value at the type level.
When working with Vec, the borrowing rule applies: you cannot add elements to the collection while holding a reference to an element. This is because Vec reallocates memory as it grows, making old references invalid. In C++, this is a runtime error; in Rust, the code fails to compile.
Use Vec when the number of elements is not known upfront, and it is the default collection of choice in Rust.
If you know how many elements there will be, reserving space upfront with with_capacity eliminates reallocations during growth.
If you frequently add and remove elements, Vec is inefficient because subsequent elements have to be shifted.
Wrong
fn main() {
let numbers = vec![1, 2, 3];
numbers.push(4);
println!("{:?}", numbers);
}Since the variable is not defined as mut, methods that modify it cannot be called; the compiler gives a "cannot borrow numbers as mutable" error and suggests adding mut. In Rust, mutation privileges must be explicitly declared.
Correct
fn main() {
let mut numbers = vec![1, 2, 3];
numbers.push(4);
println!("{:?}", numbers);
}Wrong
fn main() {
let numbers = vec![1, 2, 3];
println!("{}", numbers[10]);
}Since the index is out of bounds, the program STOPS: "index out of bounds: the len is 3 but the index is 10". Unlike in C, it doesn't read garbage data, it terminates with a clean message. If you don't want it to stop, the get method indicates at the type level that the value might not exist.
Correct
fn main() {
let numbers = vec![1, 2, 3];
match numbers.get(10) {
Some(value) => println!("{}", value),
None => println!("This index does not exist"),
}
}Wrong
fn main() {
let mut numbers = vec![1, 2, 3];
let first = &numbers[0];
numbers.push(4);
println!("{}", first);
}You cannot add to the collection while holding a reference to an element; the compiler gives a "cannot borrow numbers as mutable because it is also borrowed as immutable" error. The real reason: Vec relocates memory as it grows, leaving the old reference dangling. C++ compiles this and crashes at runtime.
Correct
fn main() {
let mut numbers = vec![1, 2, 3];
let first = numbers[0];
numbers.push(4);
println!("{}", first);
}If you are sure the index is valid, square brackets are shorter. If the index comes from user input or calculation, use get: it indicates at the type level that the value might not be there, and the program won't stop.
Iterating directly transfers ownership, so the Vec gets consumed. If you start the iteration by providing a reference, ownership is retained and you can continue using it afterwards. Writing & in a range-based loop achieves this.
Directly no, the compiler prevents it. Rust's way is the retain method: you provide a condition, and elements that don't meet the condition are deleted in a single pass. This is both safe and more efficient than a manually written loop.
Vec is a growable array and manages its own memory.
mut is required to modify it; otherwise, a compilation error occurs.
An out-of-bounds index stops the program; get reports the absence of a value.
You cannot add elements while holding a reference to an element — the compiler prevents dangling references.