为什么在编译时没有检测到这个越界错误?

Phi*_*lip 6 rust

我刚刚开始用 Rust 编码几天,在这里偶然发现了这个我不明白的案例

struct Foo {
    arr: [u8; 5]
}

fn main() {
    let foo = Foo{ arr: [0; 5] };
    let bar = &foo;
    println!("{}", bar.arr[100]);
}
Run Code Online (Sandbox Code Playgroud)

为什么这段代码可以编译?编译器看不到那里有越界错误吗?当我尝试打印时它可以检测到它foo.arr[100],那么是什么给出了呢?

kmd*_*eko 4

一般来说,并非所有在编译时检测到的错误都会报告给编译器但在这种情况下,应该会检测到它,因为 Rust 1.60 及更早版本会报告此问题,但 Rust 1.61 和 1.62 不会:

$ cargo +1.60 build
   Compiling mycrate v0.1.0 (/rust-tests)
error: this operation will panic at runtime
   --> src/main.rs:133:20
    |
133 |     println!("{}", bar.arr[100]);
    |                    ^^^^^^^^^^^^ index out of bounds: the length is 5 but the index is 100
    |
    = note: `#[deny(unconditional_panic)]` on by default
Run Code Online (Sandbox Code Playgroud)
$ cargo +1.61 build
   Compiling mycrate v0.1.0 (/rust-tests)
    Finished dev [unoptimized + debuginfo] target(s) in 0.78s
Run Code Online (Sandbox Code Playgroud)

这已被报告为问题 #98444:获取数组的共享引用会抑制 unconditional_panic lint。您可以降级您的工具链,但希望它很快就能得到解决。