We can get the size of a Vec using the .len() method:
let mut our_array = vec![50, 40, 30];
// Printing the size:
println!("{}", our_array.len()); // Output: 3
// Changing the vector:
our_array.pop();
// Printing the new size:
println!("{}", our_array.len()); // Output: 2
Using the size
We can use the size to access items from the end of a vector.
Because vectors are 0-indexed, the index of the last item is size - 1:
let our_array = vec![50, 40, 30];
let size = our_array.len();
// Printing the last item:
println!("{}", our_array[size - 1]); // Output: 30
// Printing the second to last item:
println!("{}", our_array[size - 2]); // Output: 40
Assignment
Follow the Coding Tutorial and let's play with some arrays.
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check