Start learning free

LESSON 100 OF 348 · ARRAYS I

Exceeding Vector Bounds in Rust in Rust

Lesson

When accessing vector data with indices, the most common problem we can run into is exceeding the vector's bounds.

Remember, the items of a vector are indexed from 0 to size - 1. Any index which is not in this range is invalid.

When you try to access an item with an invalid index, Rust throws an error:

let our_array = vec![50, 40, 30];

// Valid indices: 0, 1, 2
println!("{}", our_array[0]); // Output: 50
println!("{}", our_array[2]); // Output: 30

// Invalid indices: 3, 30
println!("{}", our_array[3]); // raises index out of bounds panic
println!("{}", our_array[30]); // raises index out of bounds panic
// Note: negative indices are a compile-time error in Rust

As programmers, we always want to make sure that we don't exceed one vector's bounds in our programs.


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 1
    Ctrl + Enter to check

    Exceeding Array Bounds 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