From f51f0dbb134332930d2c3477cfb69bf1559996e0 Mon Sep 17 00:00:00 2001 From: Vinh Tran Date: Wed, 25 Jun 2025 17:08:29 -0400 Subject: [PATCH] Fix typo in arrays.md (#2781) According to the error I got from trying out-of-bound index, array accesses seem to be checked at compile time. ``` Compiling playground v0.0.1 (/playground) error: this operation will panic at runtime --> src/main.rs:3:5 | 3 | a[7] = 0; | ^^^^ index out of bounds: the length is 5 but the index is 7 | = note: `#[deny(unconditional_panic)]` on by default error: could not compile `playground` (bin "playground") due to 1 previous error ``` --- src/tuples-and-arrays/arrays.md | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/src/tuples-and-arrays/arrays.md b/src/tuples-and-arrays/arrays.md index 74adac6b..f3c982e7 100644 --- a/src/tuples-and-arrays/arrays.md +++ b/src/tuples-and-arrays/arrays.md @@ -26,9 +26,34 @@ fn main() { different types. Slices, which have a size determined at runtime, are covered later. -- Try accessing an out-of-bounds array element. Array accesses are checked at - runtime. Rust can usually optimize these checks away, and they can be avoided - using unsafe Rust. +- Try accessing an out-of-bounds array element. The compiler is able to + determine that the index is unsafe, and will not compile the code: + +```rust,editable,compile_fail +fn main() { + let mut a: [i8; 5] = [5, 4, 3, 2, 1]; + a[6] = 0; + println!("a: {a:?}"); +} +``` + +- Array accesses are checked at runtime. Rust can usually optimize these checks + away; meaning if the compiler can prove the access is safe, it removes the + runtime check for better performance. They can be avoided using unsafe Rust. + The optimization is so good that it's hard to give an example of runtime + checks failing. The following code will compile but panic at runtime: + +```rust,editable,should_panic +fn get_index() -> usize { + 6 +} + +fn main() { + let mut a: [i8; 5] = [5, 4, 3, 2, 1]; + a[get_index()] = 0; + println!("a: {a:?}"); +} +``` - We can use literals to assign values to arrays.