1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-07-03 13:29:52 +02:00

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
```
This commit is contained in:
Vinh Tran
2025-06-25 17:08:29 -04:00
committed by GitHub
parent bb8b35ab74
commit f51f0dbb13

View File

@ -26,9 +26,34 @@ fn main() {
different types. Slices, which have a size determined at runtime, are covered different types. Slices, which have a size determined at runtime, are covered
later. later.
- Try accessing an out-of-bounds array element. Array accesses are checked at - Try accessing an out-of-bounds array element. The compiler is able to
runtime. Rust can usually optimize these checks away, and they can be avoided determine that the index is unsafe, and will not compile the code:
using unsafe Rust.
```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. - We can use literals to assign values to arrays.