vector
Vec<T>
let mut _v:Vec<i32> = vec![1,2,3];
(or, less common:) let _v:Vec<i32> = Vec::new()
Dynamic array that will grow or shrink as needed.
Vectors allow you to store more than one value in a single data structure that puts all the values next to each other in memory. Vectors can only store values of the same type. They are useful when you have a list of items, such as the lines of text in a file or the prices of items in a shopping cart.
Example vector:
let mut _v:Vec<i32> = vec![1,2,3];
_v.push(5);
_v.push(6);
_v.push(7);
_v.push(8);
_v.push(9);
println!("{:?}", _v);
Referencing elements inside the vector
Direct indexing:
let third: &i32 = &_v[2];
Get method:
let fourth = _v.get(3);
match fourth {
Some(fourth) => print!("The fourth element is {fourth}."),
None => println!("There is no fourth element.")
}
The borrow checker will not allow you to have an immutable reference to an element in a vector if the vector will be changed later, because adding to the vector may cause the entire thing to be moved to a different space in the memory if there is not enough room to add to it.