Sub topic 9
Indexing arrays and handling out-of-bounds access
This chapter assumes you can write basic Rust, know that an array has the type [T; N], and understand & references. It covers the two ways to read an element, what happens when the index is wrong, and when to choose each.
Indexing with square brackets
Index an array with array[i]. The index must be a usize. An i32 variable will not compile as an index, so convert it first.
fn main() {
let primes: [u32; 5] = [2, 3, 5, 7, 11];
let i: usize = 2;
println!("{}", primes[i]);
let n: i32 = 3;
println!("{}", primes[n as usize]);
}Every [] access is bounds-checked. If the index is not less than the length, the program panics at runtime and stops with a message such as index out of bounds: the len is 5 but the index is 10.
Compile-time and run-time checks
When the index is a constant and the array length is known, the compiler can reject the program itself. With let a = [1, 2, 3]; a[5], the build fails with an "this operation will panic at runtime" error. When the index comes from a variable, input, or computation, the check happens when the program runs.
Safe access with get
The get method returns an Option<&T>. You get Some(&value) for a valid index and None otherwise, so nothing panics.
fn main() {
let primes: [u32; 5] = [2, 3, 5, 7, 11];
println!("{:?}", primes.get(1));
println!("{:?}", primes.get(10));
match primes.get(10) {
Some(p) => println!("found {p}"),
None => println!("no element at index 10"),
}
let value = primes.get(10).copied().unwrap_or(0);
println!("{value}");
}The result is a reference, so copied() turns Option<&u32> into Option<u32> when you want the value itself.
Choosing between [] and get
| Situation | Use |
|---|---|
| The index is always valid by construction, such as a loop over `0..arr.len()` | `arr[i]` |
| The index comes from user input, a file, or a calculation | `arr.get(i)` |
| A bad index means a bug in your program | `arr[i]`, so the bug is loud |
| A bad index is a normal case you must handle | `arr.get(i)` |
A panic is not undefined behavior. Rust never reads memory past the end of an array in safe code. The check is what makes that guarantee, and it costs little. The optimizer often removes the check when it can prove the index is valid, such as inside iterator loops.
Common errors
- Using a signed index:
arr[-1]does not compile, andarr[n]with ani32needsas usize. Casting a negativei32produces a huge number, which then panics. - Off-by-one on the last element: the last valid index is
len() - 1. For an empty array,len() - 1underflows ausize, which panics in debug builds. - Using
[]on untrusted input: this lets bad data crash the program. Useget.
Exercise
Given let a = [10, 20, 30]; and let i = 3;, what does a[i] do at run time, and what does a.get(i) return?
Show answer
a[i] panics because the index 3 is not less than the length 3. a.get(i) returns None.