Sub topic 1
Creating and growing a Vec
Prerequisites
This chapter assumes you know basic Rust syntax (variables, functions, structs, enums), the basics of ownership and borrowing (move, &, &mut), how Option and match work, and how to run a program with cargo run.
What a Vec is
A Vec<T> is a growable list that stores values of one type T next to each other in memory. It owns its elements. When the Vec goes out of scope, every element is dropped and the memory is freed.
A Vec is made of three parts: a pointer to a heap buffer, a length (how many elements it holds), and a capacity (how many fit before it must grow). This chapter covers creating and growing a Vec. Capacity gets its own chapter later.
Creating a Vec
There are two common ways to create one.
Vec::new()makes an emptyVec. It allocates nothing until you add the first element.vec![...]is a macro that makes aVecwith starting values.
An empty Vec needs a known element type. Either annotate it, as in Vec<i32>, or let the compiler infer it from later use.
Growing and shrinking
push adds an element at the end. pop removes the last element and returns it as an Option<T>, because the Vec might be empty. Both work only on a Vec declared mut.
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)
}Here scores starts empty and gets two values. primes is created with four values in one step and is never changed, so it needs no mut. The get calls and the indexing are covered in the next chapter. For now, note that scores.pop() returns Some(72) because 72 was the last value pushed.
How a Vec grows
push is cheap most of the time. When the buffer is full, the Vec allocates a larger buffer, moves the existing elements into it, and frees the old one. Because the capacity grows by a multiple each time (not by one slot), the cost of these moves averages out to a small constant per push. This is why push is described as amortized constant time.
Common errors
- Forgetting
mut. Callingpushon a binding declared with plainletis a compile error. Addmut. - Missing type information.
let v = Vec::new();with no later use gives a "type annotations needed" error. WriteVec<i32>or push a value. - Mixed element types.
vec![1, "two"]does not compile, because aVecholds one type. A later chapter shows how to use an enum for this.
Exercise
Write a program that creates an empty Vec<String>, pushes the names "Ada" and "Grace" onto it, then pops once and prints the result. What does it print, and why is the result wrapped the way it is?
Show answer
The program is fn main() { let mut names: Vec<String> = Vec::new(); names.push(String::from("Ada")); names.push(String::from("Grace")); println!("{:?}", names.pop()); }. It prints Some("Grace"). pop removes the last element and returns an Option<String>, since the Vec could have been empty, in which case it would return None.