Sub topic 1
Creating and Growing a `Vec`
Prerequisites
Assume you know basic Rust syntax, ownership, borrowing, Option, and how to run a Cargo program. A Vec<T> is a growable, heap-allocated list whose elements all have type T.
Creating and Growing a `Vec`
Create an empty vector with Vec::new, or create one with initial values using the vec! macro. The type annotation is sometimes needed when Rust cannot infer the element type.
fn main() {
let mut scores: Vec<i32> = Vec::new();
scores.push(90);
scores.push(72);
let primes = vec![2, 3, 5, 7];
println!("{:?}", scores.get(1)); // Some(72)
println!("{:?}", scores.get(5)); // None
println!("{}", primes[2]); // 5
println!("{:?}", scores.pop()); // Some(72)
}push adds an item to the end. pop removes and returns the last item as an Option<T>. A vector must be mutable to change it.
Reading Elements: Indexing vs `get`
Indexing, such as primes[2], returns the element directly. It panics if the index is outside the vector. Use it when an invalid index indicates a programming error.
get returns Option<&T>. It returns Some for a valid index and None otherwise. Use it when the index may be invalid and should be handled safely.
Iterating over a `Vec`
The form of the for loop determines what happens to the vector:
for item in &viterates by shared reference. The vector remains usable.for item in &mut viterates by mutable reference and allows changes.for item in vmoves the vector into the loop. You cannot usevafterward.
fn main() {
let mut v = vec![1, 2, 3];
for x in v.iter_mut() {
*x *= 2;
}
let total: i32 = v.iter().sum();
println!("{:?} {}", v, total); // [2, 4, 6] 12
}Why You Cannot Push While Holding a Reference
A vector may reallocate its storage when it grows. Any reference into that storage could then point to invalid memory. Rust prevents this by rejecting a push while a reference into the vector is still active.
Copy the value when you only need the value, or finish using the reference before modifying the vector.
Exercise
Which loop should you use to double every element in a vector without moving the vector?
Show answer
Use for item in &mut v or for item in v.iter_mut().