How does Rust's compiler check that an array is out of bounds?

fn main() {
    let a = [1,2, 3, 4, 5];
    println!("a6 is {}", a[6]);
}

cargo build
> Compiling rust_test v0.1.0 (E:\code\rust_test)

error: index out of bounds: the len is 5 but the index is 6
 --> src\main.rs:3:26
  |
3 |     println!("a6 is {}", a[6]);
  |                          ^^^^
  |
  = note: #[deny(const_err)] on by default
error: aborting due to previous error
1 Like

In this case you are indexing with a constant and it was able to notice at compile time, but usually it isn't and it will panic at runtime.

5 Likes

And, to add to that, it's important that you are indexing an array, of which the size is known at compile time (because it is part of its type). If you indexed a slice, the error would move to runtime instead (playground).

2 Likes