E0902: Index out of bounds
| Code | Category | Stability |
|---|---|---|
E0902 | Array | Permanent |
Explanation
A constant index into a fixed array is bounds-checked while the program is compiled (4.11:7, 7.1:9). E0902 reports an index the compiler folded to a constant that is negative or not less than the array's length, so the access could never succeed; the message names the length and the index it evaluated. Only constant indices are diagnosed here. A non-constant index is checked at run time and traps instead of failing the build (4.11:8, 4.11:9), and a slice index is always dynamic because a view's length is a runtime value (7.2:22). The check follows the whole place chain rather than only a whole-expression read: xs[5].field names the same out-of-range element that xs[5] does, and reports at the index in every place context — a value read, a comparison operand, a borrow argument, an @dbg operand.
Likely cause
The index is one past the end: the valid indices of [T; N] are 0 through N - 1. An array's length was often reduced without updating a fixed index, or a length was mistaken for a last position. Use an index inside the range. A position that is only known at run time is not diagnosed here at all — it is bounds-checked at run time and traps, halting the program with exit code 101.
Examples
A constant index past the last element
fn main() -> i32 {
let xs: [i32; 3] = [10, 20, 30];
xs[5]
}
Index the last valid position
fn main() -> i32 {
let xs: [i32; 3] = [10, 20, 30];
xs[2]
}