liveBook · Manning

Vector

As explained in Learn Rust in a Month of Lunches

A vector is Rust's growable, heap-allocated sequence type whose elements share a type.

A vector, written Vec, is Rust’s growable collection for values that all share one type. Unlike an array, its size can change while the program runs. section 3.1.2 section 3.3

Create and use vectors in several straightforward ways:

  • Use Vec::new() with push(); Rust can infer the element type from the values you add. section 3.1.2
  • Write the type explicitly, such as Vec<String>, when the compiler needs guidance. section 3.1.2
  • Use the vec! macro for compact initialization, such as vec![8, 10, 10]. section 3.1.2
  • Keep every element the same type; Vec<String> cannot accept an i32. section 3.1.2
  • Take slices with ranges, including a middle range, an open-ended range, or the complete vector. section 3.1.2

Vectors allocate memory on the heap and track capacity, the amount of space currently reserved. Pushing values uses that space; when it is exceeded, the capacity can grow, shown by examples changing from 4 to 8. Vec::with_capacity lets you reserve space in advance. section 3.1.2

A growable list of names

let mut names = Vec::new(); names.push(String::from("Windy")); names.push(String::from("Gomesy")); The vector starts empty, then grows as two String values are pushed into it.

fn main() {
    let mut my_vec = vec![8, 10, 10];
}

Inspect the compact vec! macro example to see how several values can initialize a vector at once. section 3.1.2

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains construction, element types, slicing, capacity, growth, and preallocation through focused examples.
Examples
Uses name vectors, integer vectors, vector slices, nested vectors, and capacity-printing programs.
What it assumes
Assumes basic Rust values and types while defining collection terminology and homogeneous vector elements.
What you can do after
Build vectors with Vec::new, vec!, push, explicit types, slicing, and Vec::with_capacity.
How it connects
Connects vectors with arrays, String, tuples, slices, type inference, and heap allocation.

Also explained in

Compare how 11 books explain vector →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.