Sub topic 9
Indexing arrays and handling out-of-bounds access
This chapter assumes you can write and run a Rust program with cargo, and that you know how to declare an array such as [u32; 5]. It covers how indexing works, when it fails, and which tool to use for each kind of failure.
Indexing with square brackets
You read an array element with array[index]. The first element is at index 0. The index must be a usize, the unsigned integer type that matches the platform's pointer size.
fn main() {
let primes: [u32; 5] = [2, 3, 5, 7, 11];
let i = 2;
println!("{}", primes[i]);
let last = primes[primes.len() - 1];
println!("{last}");
}The variable i has no annotation. The compiler infers usize because it is used as an index. If you declare let i: i32 = 2;, then primes[i] fails to compile, because the type [u32; 5] cannot be indexed by i32. Rust never converts an index silently. Write primes[i as usize] only after you have checked that i is not negative. A negative value would turn into a huge usize.
What happens when the index is too big
Rust checks every index against the array length. An invalid index never reads neighboring memory. There are two outcomes, depending on whether the compiler can see the problem.
Detected at compile time
If the array length and the index are both known constants, the compiler rejects the program.
fn main() {
let a = [1, 2, 3];
println!("{}", a[5]);
}error: this operation will panic at runtime
--> src/main.rs:3:20
|
3 | println!("{}", a[5]);
| ^^^^ index out of bounds: the length is 3 but the index is 5
|
= note: `#[deny(unconditional_panic)]` on by defaultThis is a lint that is set to deny by default. It catches only simple cases. A value that passes through a function call or a runtime computation is usually invisible to it.
Detected at run time
When the index comes from input, the check happens while the program runs. A failed check causes a panic, which unwinds the thread and normally ends the program.
use std::env;
fn main() {
let data = [10, 20, 30];
let index: usize = env::args()
.nth(1)
.and_then(|s| s.parse().ok())
.unwrap_or(0);
println!("data[{index}] = {}", data[index]);
}Running cargo run -- 7 prints a message like this and exits with a non-zero status:
thread 'main' panicked at src/main.rs:10:34:
index out of bounds: the len is 3 but the index is 7The check stays in release builds. It is a safety guarantee, not a debug feature. Only the optimizer may remove it, and only when it can prove the index is valid.
Non-panicking access with get
The get method takes an index and returns Option<&T>. It gives Some for a valid index and None otherwise. This turns the failure into a value you must handle.
fn main() {
let mut data = [10, 20, 30];
match data.get(7) {
Some(v) => println!("found {v}"),
None => println!("index 7 is out of range"),
}
let second = data.get(1).copied().unwrap_or(0);
println!("{second}");
if let Some(slot) = data.get_mut(2) {
*slot += 5;
}
println!("{:?}", data);
}Three points about this code:
getreturns a reference, socopied()turnsOption<&i32>intoOption<i32>forCopytypes.get_mutreturnsOption<&mut T>. It lets you modify an element without risking a panic.first()andlast()are shortcuts forget(0)andget(len - 1). They also returnOption, and they handle empty slices correctly.
Choosing between [] and get
| Access | Out of bounds | Use when |
|---|---|---|
| `a[i]` | Panics | An invalid index means a bug in your program |
| `a.get(i)` | Returns `None` | The index comes from outside input or a calculation that can fail |
| `a.first()`, `a.last()` | Returns `None` if empty | You want the ends of a sequence that may be empty |
| `a[i]` with a prior check | Panics only if the check is wrong | You have just compared `i` against `len()` |
Indexing with [] is the right choice when the index is known to be valid by construction, such as a loop counter bounded by len(). Reaching for get everywhere adds noise. Use it where being wrong is a normal event.
Slicing ranges can panic too
Range indexing follows the same rules. &a[1..3] borrows part of the array as a slice. If the range end exceeds the length, or the start is greater than the end, it panics. The get method accepts ranges and returns Option<&[T]>.
fn main() {
let data = [1, 2, 3, 4];
println!("{:?}", data.get(1..3));
println!("{:?}", data.get(2..9));
println!("{:?}", data.get(..=3));
let (left, right) = data.split_at(2);
println!("{:?} {:?}", left, right);
}This prints Some([2, 3]), None, Some([1, 2, 3, 4]), and then [1, 2] [3, 4]. The split_at method panics if its argument is larger than the length. Its sibling split_at_checked returns an Option instead.
Computing indexes safely
Most real out-of-bounds bugs come from index arithmetic. There are two typical cases.
Subtracting from a usize can underflow. In a debug build, 0usize - 1 panics with an overflow message. In a release build it wraps to the largest usize, and the next bounds check then panics. Either way, use checked_sub to make the failure explicit.
Wrapping around the end needs the remainder operator.
fn previous(data: &[i32], i: usize) -> Option<i32> {
let j = i.checked_sub(1)?;
data.get(j).copied()
}
fn wrap(data: &[i32; 4], i: usize) -> i32 {
data[i % data.len()]
}
fn main() {
let data = [5, 6, 7, 8];
println!("{:?}", previous(&data, 0));
println!("{:?}", previous(&data, 2));
println!("{}", wrap(&data, 9));
}The output is None, Some(6), and 6. In wrap, the remainder is always less than len(), so the index is valid. The program cannot panic there unless the array is empty, because i % 0 panics. For a [i32; 4] that cannot happen.
Prefer iteration over indexing
Many loops that use an index only need the elements. An iterator has no index to get wrong.
fn main() {
let data = [3, 8, 2];
for i in 0..data.len() {
print!("{} ", data[i]);
}
println!();
for value in data.iter() {
print!("{value} ");
}
println!();
for (i, value) in data.iter().enumerate() {
print!("{i}:{value} ");
}
println!();
}All three loops are correct. The first is the pattern to avoid when you do not need the index, because it has a bounds check on every pass and invites off-by-one errors such as 0..=data.len(). The enumerate form gives you the position when you need it.
Common mistakes
- Using
<=in a range.0..=data.len()includes an index equal to the length, which is always out of bounds. - Indexing an empty slice.
values[0]panics on&[]. Usefirst()when the input may be empty. - Casting a negative number.
-1_i32 as usizeis18446744073709551615on a 64-bit platform. Convert withusize::try_from(n).ok()and handle theNone. - Assuming the compiler will always warn. The compile-time lint only works for constants.
Exercise
Write a function middle_or_none(values: &[i32]) -> Option<i32> that returns the middle element of an odd-length slice and None for an even-length or empty slice. Do it without using [] indexing. What does middle_or_none(&[4, 9, 1]) return?
Show answer
Use get with the computed middle index after checking the length is odd.
fn middleornone(values: &[i32]) -> Option<i32> {
if values.len() % 2 == 1 {
values.get(values.len() / 2).copied()
} else {
None
}
}
For &[4, 9, 1] the length is 3, the middle index is 1, and the result is Some(9). An empty slice has length 0, which is even, so the result is None.
Exercise
Given let a = [1, 2, 3]; and let n: i32 = 1;, why does a[n] fail to compile, and what is the safest fix if n might be negative?
Show answer
Arrays and slices are indexed by usize, and Rust does not convert i32 to usize implicitly. If n might be negative, avoid n as usize because it wraps. Use usize::try_from(n).ok().and_then(|i| a.get(i)), which returns None for negative or too-large values.