100-exercises-to-learn-rust icon indicating copy to clipboard operation
100-exercises-to-learn-rust copied to clipboard

Out-of-bounds access already checked at compile time

Open EugenDueck opened this issue 8 months ago • 0 comments

On https://github.com/mainmatter/100-exercises-to-learn-rust/blob/main/book/src/06_ticket_management/01_arrays.md , it reads:

Out-of-bounds access

If you try to access an element that's out of bounds, Rust will panic:

let numbers: [u32; 3] = [1, 2, 3];
let fourth = numbers[3]; // This will panic

This is enforced at runtime using bounds checking. It comes with a small performance overhead, but it's how Rust prevents buffer overflows.\

However, this won't even compile:

error: this operation will panic at runtime
  --> exercises/06_ticket_management/01_arrays/src/lib.rs:28:22
   |
28 |         let fourth = numbers[x]; // This will panic
   |                      ^^^^^^^^^^ index out of bounds: the length is 3 but the index is 3
   |
   = note: `#[deny(unconditional_panic)]` on by default

Not sure if that's a recent change to rustc (I used 1.85.1), but I wanted to check it out, because I was surprised that the compiler wouldn't prevent this with an error.

The following will however not get caught by the compiler and indeed result in a runtime panic:

fn test(x: usize) {
    let numbers: [u32; 3] = [1, 2, 3];
    let fourth = numbers[x]; // This will panic
}
// ...
    test(3);

EugenDueck avatar Apr 05 '25 06:04 EugenDueck