"index out of bounds" compilation error not found sometimes

With this code, there's a compilation error: "index out of bounds: the length is 3 but the index is 3":

fn main() {
    let a = [1, 2, 3];
    // let b = a.len();
    let c = a[3];
}

With this code, there's no compilation error, but there's a runtime panic: "index out of bounds: the len is 3 but the index is 3":

fn main() {
    let a = [1, 2, 3];
    let b = a.len();
    let c = a[3];
}

Is this expected? It doesn't seem like it, but I'm pretty new to Rust.

I'm using the latest stable version of Rust:

$ cargo --version
cargo 1.64.0 (387270bc7 2022-09-16)

FYI, I noticed this when experimenting with the example code at Arrays and Slices - Rust By Example. At the end of the example code there, there's commented-out code with a comment of: "Out of bound indexing causes compile error". I uncommented that code and there was no compilation error but, rather, a runtime panic.

1 Like

I think this is issue #98444, so it is a known bug that ought to be fixed eventually.


Also see this comment, which refers to "Arrays and Slices" in "Rust By Example".

1 Like

Detection at compile time of out of bounds panics is done on a best effort basis. Anything too complex to detect will be ignored. In general I would not expect it to work.

4 Likes

It's right that you shouldn't rely on all errors like that being caught at compile-time. However, the particular case seems to have worked in Rust 1.60 but no longer in 1.61. So it's a regression that should be fixed. Not sure if you can rely on it in future though, I think there's no guarantee given by the compiler that these sort of errors are always caught at compile-time.