Vectors are the primary linear collection type in Rust. They are mutable, growable lists of values, represented as a struct in memory.
Vectors can be initialised in two main ways:
fn main() {
let mut fstvec: Vec<i32> = Vec::new(); // Constructor method
fstvec.push(10);
fstvec.push(5);
let sndvec: Vec<f64> = vec![2.643, 4.219, 9.263]; // vec! macro
println!("{:?} {:?}", fstvec, sndvec)
}
As can be seen in the above example, there is a shorthand macro, vec!, for quickly initialising a vector and immediately filling it with values (although empty vectors can still be made by leaving the macro's square brackets empty). The shorthand syntax that can be used with arrays can also be used with this macro:
fn main() {
let vec: Vec<f64> = vec![23.45673; 10]; // creates vector with ten elements equal to this float
println!("{:?}", vec)
}
As with arrays, individual elements of vectors can be accessed with indexing...:
fn main() {
let vec: Vec<i32> = vec![56, 23, 78, 92, 108];
println!("{}", vec[2]) // prints 78 (zero-indexed)
}
...and iterated over with loops:
fn main() {
let vec: Vec<i32> = vec![12, 43, 5, 78, 32];
for v in vec {
println!("{}", v);
}
}
Exercise:
Try initialising a vector of chars, before iterating over it with .iter() (remember the page on arrays and slices?):
Vectors also have a multitude of useful built-in methods (such as push(), demonstrated above) that allow for easily accessible operations on them and their elements. For example: