Sub topic 4
Out-of-range access: indexing vs get
This chapter assumes you know basic Rust syntax, ownership, references, and how arrays and Vec<T> work. You should also know what a slice &[T] is and how range syntax such as &a[1..4] creates one. Here you will learn what happens when an index or range is wrong, and how to choose between two ways of handling it.
Two ways to ask for an element
Rust gives you two ways to read from a slice, array, or vector by position.
- Indexing with
[], as inv[5]or&v[1..5]. If the position is out of range, the program panics. A panic stops the current thread and prints an error message. - The
getmethod, as inv.get(5)orv.get(1..5). It returns anOption. You getSome(value)when the position is valid andNonewhen it is not.
Both checks happen at run time. Rust never reads memory outside the slice. The only difference is how a failure is reported to you.
What panicking indexing looks like
This program compiles, but it panics when it runs:
fn main() {
let v = vec![1, 2, 3];
let i = v.len() + 2;
println!("{}", v[i]);
}The output ends with a message like index out of bounds: the len is 3 but the index is 5. Range indexing panics in the same way. For example, &v[1..5] fails with range end index 5 out of range for slice of length 3. A range whose start is greater than its end, such as &v[3..1], panics too.
Indexing is the right choice when an out-of-range value would mean a bug in your program. A panic makes that bug visible right away, close to its cause.
Handling failure with get
get turns the same failure into a normal value you can inspect. The next example shows several cases:
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][..]));
let s = "héllo";
assert_eq!(&s[0..1], "h");
assert_eq!(s.get(0..2), None); // byte 2 is inside the two-byte 'é'
}Notice three things.
getaccepts either a singleusizeor a range. With a single number it returnsOption<&T>. With a range it returnsOption<&[T]>.- The result borrows from the original data.
getdoes not copy anything. - The last line applies to strings. A
stris UTF-8 text, and an index must fall on a character boundary. The letterétakes two bytes, so byte 2 sits in the middle of it.s.get(0..2)returnsNone, while&s[0..2]would panic. The next chapter covers string slices in detail.
Choosing between them
| Situation | Better choice |
|---|---|
| The index comes from user input, a file, or a network message | `get` |
| You loop with `0..v.len()` and the bound is obvious | indexing, or better, an iterator |
| An out-of-range value would be a bug in your logic | indexing |
| You want a default when the position is missing | `get` with `unwrap_or` |
| You want to report a clear error to the caller | `get` with `ok_or` and `?` |
A useful rule: use get when the data is untrusted or the failure is expected, and use indexing when failure means your own code is wrong.
Here is a function that reads a value safely and gives the caller a useful error:
fn third(values: &[i32]) -> Result<i32, String> {
values
.get(2)
.copied()
.ok_or_else(|| format!("need at least 3 values, got {}", values.len()))
}
fn main() {
println!("{:?}", third(&[1, 2, 3, 4]));
println!("{:?}", third(&[1, 2]));
}This prints Ok(3) and then Err("need at least 3 values, got 2"). The copied call turns Option<&i32> into Option<i32>.
Common mistakes
- Calling
get(i).unwrap(). This panics just like indexing, but with a less helpful message. Either index directly or handle theNone. - Forgetting that a range can be valid at one end only.
&v[..5]fails on a three-element vector even though the start is fine. - Slicing a
&strat a byte offset you computed yourself. Offsets fromfindare safe, but arbitrary numbers may land inside a character. - Checking
i < v.len()and then indexing. This works, butgetdoes the check and the access in one step, which is harder to get wrong.
The flow of a checked access
Exercise
Given let v = vec![10, 20, 30];, what does each of these do: v.get(3), v.get(1..3), and &v[1..4]?
Show answer
v.get(3) returns None, because the valid indexes are 0 to 2. v.get(1..3) returns Some(&[20, 30][..]), because the end of a range is exclusive and may equal the length. &v[1..4] panics, because the end index 4 is greater than the length 3.
Exercise
Write a function last_two(values: &[i32]) -> Option<&[i32]> that returns the final two elements, or None when there are fewer than two.
Show answer
fn last_two(values: &[i32]) -> Option<&[i32]> { let n = values.len(); if n < 2 { None } else { values.get(n - 2..) } } — the length check prevents n - 2 from underflowing, and get(n - 2..) returns the tail as Some.