You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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:
fntest(x:usize){let numbers:[u32;3] = [1,2,3];let fourth = numbers[x];// This will panic}// ...test(3);
The text was updated successfully, but these errors were encountered:
EugenDueck
changed the title
Out-of-bounds access
Out-of-bounds access actually already checked at compile
Apr 5, 2025
EugenDueck
changed the title
Out-of-bounds access actually already checked at compile
Out-of-bounds access already checked at compile time
Apr 5, 2025
On https://github.com/mainmatter/100-exercises-to-learn-rust/blob/main/book/src/06_ticket_management/01_arrays.md , it reads:
However, this won't even compile:
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:
The text was updated successfully, but these errors were encountered: