Sub topic 4
Out-of-range access: indexing vs get
This chapter assumes you can create slices with range syntax such as &v[1..4], and that you know Option and match. It covers what happens when an index or range doesn't fit the slice, and how to choose between the two ways of asking for an element.
Two ways to ask for an element
Every slice, array, and Vec<T> supports two access styles.
- Indexing with
s[i]or&s[a..b]. It returns the element or sub-slice directly. If the position is invalid, the program panics. getwiths.get(i)ors.get(a..b). It returns anOption. If the position is invalid, you getNone.
Both do the same bounds check. They differ only in what happens when the check fails.
fn main() {
let v = vec![10, 20, 30];
let i = v.len() + 2;
match v.get(i) {
Some(x) => println!("v[{i}] = {x}"),
None => println!("index {i} is out of range for length {}", v.len()),
}
// Uncommenting the next line panics:
// println!("{}", v[i]);
}This prints index 5 is out of range for length 3.
What indexing does on failure
s[i] calls the Index trait. For slices, the implementation compares the index to the length and calls a panic routine if the index is too large. A panic prints a message and unwinds the current thread. In a single-threaded program that ends the process with a non-zero exit code.
The message depends on the form of the index.
| Expression (slice of length 3) | Panic message |
|---|---|
| `v[5]` | `index out of bounds: the len is 3 but the index is 5` |
| `&v[1..5]` | `range end index 5 out of range for slice of length 3` |
| `&v[4..]` | `range start index 4 out of range for slice of length 3` |
| `&v[3..2]` | `slice index starts at 3 but ends at 2` |
| `&v[..=3]` | `range end index 4 out of range for slice of length 3` |
The last row catches many people. An inclusive range ..=3 means "up to and including index 3", which needs a length of at least 4. The panic message reports the internal exclusive end, 4.
Valid edge cases
Some ranges look suspicious but are valid.
&v[3..]on a length-3 slice is valid and returns an empty slice. A start equal to the length is allowed.&v[3..3]is valid and empty.&v[..]on an empty slice is valid and returns an empty slice.v[0]on an empty slice panics, because there is no element at index 0.
The rule is that a range a..b is valid when a <= b <= len. A single index i is valid when i < len.
Index types
Slice indices must be usize. Indexing with an i32 or u32 variable is a compile error, so you convert explicitly:
fn main() {
let v = [1, 2, 3, 4];
let i: u32 = 2;
println!("{}", v[i as usize]);
}There are no negative indices. This produces a trap with subtraction. If i is a usize equal to 0, then i - 1 underflows. In a debug build that panics with "attempt to subtract with overflow". In a release build it wraps around to a huge number, and the following index then panics with an out-of-bounds message. Either way the failure shows up far from the cause. Use checked_sub when the result feeds an index.
fn previous(v: &[i32], i: usize) -> Option<&i32> {
let p = i.checked_sub(1)?;
v.get(p)
}
fn main() {
let v = [5, 6, 7];
println!("{:?}", previous(&v, 2));
println!("{:?}", previous(&v, 0));
}This prints Some(6) and then None.
What `get` does
get is a method on slices, and it accepts either a usize or any range type. The return type follows the argument.
| Call | Returns |
|---|---|
| `s.get(i)` | `Option<&T>` |
| `s.get(a..b)` | `Option<&[T]>` |
| `s.get_mut(i)` | `Option<&mut T>` |
| `s.get_mut(a..b)` | `Option<&mut [T]>` |
This works through the SliceIndex trait. Both usize and the range types implement it, so one method name covers both.
fn main() {
let v = vec![1, 2, 3];
assert_eq!(v.get(5), None);
assert_eq!(v.get(1..5), None);
assert_eq!(v.get(1..), Some(&[2, 3][..]));
assert_eq!(v.get(3..), Some(&[][..]));
assert_eq!(v.get(2..1), None);
let s = "héllo";
assert_eq!(&s[0..1], "h");
assert_eq!(s.get(0..2), None); // byte 2 is inside the two-byte 'é'
println!("all checks passed");
}Two details to notice.
v.get(3..)isSomewith an empty slice, matching the valid edge cases above.strhas its ownget. For strings, a range can also fail because it cuts through a multi-byte character, as thes.get(0..2)line shows. The next chapter covers that case in detail.
Mutation through `get_mut`
get_mut gives you a mutable reference only if the position exists.
fn main() {
let mut scores = vec![10, 20, 30];
if let Some(slot) = scores.get_mut(1) {
*slot += 5;
}
if let Some(tail) = scores.get_mut(2..) {
tail[0] = 99;
}
println!("{:?}", scores);
}This prints [10, 25, 99].
Handling the `None` case
get is only useful if you decide what None means. Common patterns:
fn main() {
let v = vec![4, 8, 15];
let i = 7;
// 1. A default value.
let a = v.get(i).copied().unwrap_or(0);
// 2. Branching.
if let Some(x) = v.get(i) {
println!("found {x}");
} else {
println!("nothing at {i}");
}
// 3. Converting to an error for the caller.
let r: Result<i32, String> = v
.get(i)
.copied()
.ok_or_else(|| format!("index {i} out of range (len {})", v.len()));
println!("{a} {:?}", r);
}This prints nothing at 7, then 0 Err("index 7 out of range (len 3)").
The copied() call turns Option<&i32> into Option<i32>. It works for Copy types. For other types, use cloned() or keep the reference.
For the ends of a slice, prefer the dedicated methods first(), last(), split_first(), and split_last(). They return Option and make the intent clearer than get(0) or get(len - 1). The len - 1 form underflows on an empty slice.
A realistic case: parsing a byte buffer
Data from files and networks is the main reason to use get. The buffer's size is not under your control, so a bad length must be an error, not a crash.
fn read_u16(buf: &[u8], offset: usize) -> Option<u16> {
let end = offset.checked_add(2)?;
let bytes = buf.get(offset..end)?;
Some(u16::from_be_bytes([bytes[0], bytes[1]]))
}
fn main() {
let packet = [0x00, 0x2A, 0x01];
println!("{:?}", read_u16(&packet, 0));
println!("{:?}", read_u16(&packet, 1));
println!("{:?}", read_u16(&packet, 2));
println!("{:?}", read_u16(&packet, usize::MAX));
}The output is Some(42), Some(298), None, None.
Two points here. First, checked_add guards the addition offset + 2. Without it, an offset near usize::MAX would overflow, which panics in debug builds and wraps to a small number in release builds, so the check passes on the wrong range. Second, bytes[0] and bytes[1] are safe to index. get has just proved the slice has exactly two elements.
When indexing is the right choice
A panic signals a bug in the program, not a condition the program expects. Indexing is correct when an invariant you control makes failure impossible, or when failure would mean the code itself is wrong.
- A loop
for i in 0..v.len()that indexesv[i]. - A fixed-size array indexed by a value you have already limited, such as
i % 8on an[T; 8]. - A slice whose length you checked a line earlier, such as
if buf.len() < 4 { return Err(..) }followed bybuf[0..4]. - Tests and short examples, where a panic with a clear message is exactly the failure you want.
Use get when the index or range comes from outside the code: user input, file contents, network data, or arithmetic that can overflow. Using get there turns bad input into a value you can handle.
Don't use get(i).unwrap() as a substitute for v[i]. It panics with a less useful message ("called Option::unwrap() on a None value"), which does not tell you the index or the length. If you want a panic, write v[i]. If you want a custom message, use expect.
Compile-time detection and iterators
Indexing an array with a constant out-of-range index is caught at compile time. The lint unconditional_panic is deny-by-default, so this does not build:
fn main() {
let a = [1, 2, 3];
println!("{}", a[5]);
}The compiler reports "this operation will panic at runtime". The check only applies to arrays and constant indices. For Vec and for runtime values, the compiler cannot know the length, and the failure appears at runtime.
You can often avoid the question entirely. Iterators visit each element without an index, so there is nothing to go out of range.
fn main() {
let v = vec![3, 1, 4, 1, 5];
let total: i32 = v.iter().sum();
for (i, x) in v.iter().enumerate() {
println!("{i}: {x}");
}
println!("total {total}");
}Performance
The bounds check is always present, in debug and release builds alike. Rust does not remove it for speed. The optimizer drops a check when it can prove the index is valid, for example in a loop bounded by v.len(). In hot loops where it cannot, iterators or a single up-front slice such as let v = &v[..n]; give the optimizer the length once. Measure before changing code for this reason, since a branch that is predicted correctly costs little.
get_unchecked skips the check but is unsafe. Out-of-range use is undefined behavior, not a panic, so it can corrupt memory silently. Treat it as a last resort after profiling shows a real cost.
Common errors
- Off-by-one in inclusive ranges.
&v[0..=v.len()]panics. Use&v[0..v.len()]or&v[..]. - Subtraction on
usize.v[i - 1]fails wheniis 0. Usechecked_sub. - Overflow in
start + len. Usechecked_addwhen either value comes from outside. - Range with start greater than end.
&v[b..a]withb > apanics even if both values are less than the length. - Unwrapping
getimmediately. It hides the index and length in the panic message. Preferv[i]orexpectwith context. - Mixing integer types. An index must be
usize. Convert withas usizeonly when the value is known to be non-negative, or useusize::try_from(x)when it might not be.
Exercises
Exercise
A function receives data: &[u8] and n: usize and must return the first n bytes, or None if there are fewer than n bytes. Write the body in one line, then say what it returns for n == data.len() and for n == data.len() + 1.
Show answer
data.get(..n). For n == data.len() it returns Some(data) (the whole slice), because ..n is valid when n <= len. For n == data.len() + 1 it returns None.
Exercise
The code let i: usize = 0; let x = v[i - 1]; behaves differently in debug and release builds. Describe both behaviors and give a fix that returns an Option<&i32>.
Show answer
In a debug build, i - 1 panics with "attempt to subtract with overflow". In a release build the subtraction wraps to usize::MAX, and the index then panics with "index out of bounds". Fix: i.checked_sub(1).and_then(|p| v.get(p)).
Exercise
Which of these panic when v is vec![1, 2, 3]: &v[3..], &v[..=3], &v[2..1], v.get(9)?
Show answer
&v[..=3] panics because it needs length 4. &v[2..1] panics because the start is greater than the end. &v[3..] is valid and returns an empty slice. v.get(9) does not panic and returns None.