Start learning free

LESSON 98 OF 348 · ARRAYS I

Vector Size in Rust in Rust

Lesson

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.


STEP 1 OF 3
    Ctrl + Enter to check

    Array Length in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free