Vectors

Are growable and dynamically typed lists of any type created on the heap.

let v = vec![1, 2, 3, 4, 5, 6]; // v: Vec<i32>

is the type, Vec<T> which means Vectors can be of any type (Generic Data Types (T))

the brackets are actually a convention, so you could technically use () too.

Vectors are contiguous chunks of memory allocated on the Heap, the compiler needs to know the size of the vector at compile time, but if that is an obstacle you can use the [[Box type]] instead.

you can access vectors like normal arrays: v[1];

Iterating


#![allow(unused_variables)]
fn main() {
let mut v = vec![1, 2, 3, 4, 5];
 
for i in &v {
    println!("A reference to {}", i);
}
 
for i in &mut v {
    println!("A mutable reference to {}", i);
}
 
for i in v {
    println!("Take ownership of the vector and its element {}", i);
}
 
}

the last vector iteration would not work if you did it before the firs two because you are taking Ownership of the vector and it would be dropped from memory once the for loop is out-of-scope.

the first two you can repeat over and over.

Common methods in using Vectors


  • push()
  • pop()
  • len()