Skip to content

Commit f51f0db

Browse files
authored
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 ```
1 parent bb8b35a commit f51f0db

File tree

1 file changed

+28
-3
lines changed

1 file changed

+28
-3
lines changed

src/tuples-and-arrays/arrays.md

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,34 @@ fn main() {
2626
different types. Slices, which have a size determined at runtime, are covered
2727
later.
2828

29-
- Try accessing an out-of-bounds array element. Array accesses are checked at
30-
runtime. Rust can usually optimize these checks away, and they can be avoided
31-
using unsafe Rust.
29+
- Try accessing an out-of-bounds array element. The compiler is able to
30+
determine that the index is unsafe, and will not compile the code:
31+
32+
```rust,editable,compile_fail
33+
fn main() {
34+
let mut a: [i8; 5] = [5, 4, 3, 2, 1];
35+
a[6] = 0;
36+
println!("a: {a:?}");
37+
}
38+
```
39+
40+
- Array accesses are checked at runtime. Rust can usually optimize these checks
41+
away; meaning if the compiler can prove the access is safe, it removes the
42+
runtime check for better performance. They can be avoided using unsafe Rust.
43+
The optimization is so good that it's hard to give an example of runtime
44+
checks failing. The following code will compile but panic at runtime:
45+
46+
```rust,editable,should_panic
47+
fn get_index() -> usize {
48+
6
49+
}
50+
51+
fn main() {
52+
let mut a: [i8; 5] = [5, 4, 3, 2, 1];
53+
a[get_index()] = 0;
54+
println!("a: {a:?}");
55+
}
56+
```
3257

3358
- We can use literals to assign values to arrays.
3459

0 commit comments

Comments
 (0)