When accessing array data with indices, the most common problem we can run into is exceeding the array's bounds.
Remember, the items of an array are indexed from 0 to length - 1. Any index which is not in this range is invalid.
When you try to access an item with an invalid index, Rust reports an index out of bounds error. With a constant index on an array, as below, the compiler rejects the program (this operation will panic at runtime); with an index computed while the program runs, it panics with index out of bounds instead:
let my_array = [50, 40, 30];
// Valid indices: 0, 1, 2
println!("{}", my_array[0]); // Output: 50
println!("{}", my_array[2]); // Output: 30
// Invalid indices: 3, 30
println!("{}", my_array[3]); // compile error: index out of bounds
println!("{}", my_array[30]); // compile error: index out of bounds
// Note: negative indices are a compile-time error in Rust
As programmers, we always want to make sure that we don't exceed one array'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.
Free plan: 30 tutor messages. PRO is unlimited.
