A vector is a collection of items of the same type.

rust
// Create an empty mutable empty vector.
// The type of the elements must be annotated.
let mut stuff_and_things: Vec<&str> = Vec::new();

// Add items to the vector.
stuff_and_things.push("stuff");
stuff_and_things.push("things");

// Access the elements of a vector with square brackets and the index number.
println!("{}", stuff_and_things[0]); // => stuff
println!("{}", stuff_and_things[1]); // => things

// Accessing an element that is out of bounds will result in a panic.
println!("{}", stuff_and_things[2]); // => PANIC!

// Create an immutable vector with 2 elements using the literal syntax.
let stuff_and_things = vec!["stuff", "things"];

// Specify the type annotation
let stuff_and_things: Vec<&str> = vec!["stuff", "things"];

// Create a mutable vector with the literal syntax
let mut stuff_and_things = vec!["stuff", "things"];

Vector Considerations

  • When an empty vector is created with Vec::new it is un-allocated until elements are pushed into it.
  • A vector with elements has allocated memory and lives on the heap.
  • A vector is represented as a pointer to the data a length and a capacity.
  • If a vector needs to grow past the size of its capacity, the vector is re-allocated with additional memory.
  • A vectors size is not known at compile time, they can grow or shrink at run time.

Tags

rust