Vectors
-
Is a similar collection type to the Array, provided by the standard library, that is allowed to grow or shrink in size.
Creation
let mut v = Vec::new();
v.push(5);
v.push(6);
v.push(7);
v.push(8);
let v = vec![1, 2, 3];
Access
-
Without handling Out of Bounds:
let v = vec![1, 2, 3, 4, 5]; let third: &i32 = &v[2]; println!("The third element is {third}"); -
Handling Out of Bounds:
let third: Option<&i32> = v.get(2); match third { Some(third) => println!("The third element is {third}"), None => println!("There is no third element."), } -
Getting all elements:
let v = vec![100, 32, 57]; for i in &v { println!("{i}"); } -
Mutating with the
*dereference operator.let mut v = vec![100, 32, 57]; for i in &mut v { *i += 50; }