Sub topic 2
Reading elements: indexing vs get
This chapter assumes you know basic Rust syntax, ownership and borrowing (move, &, &mut), Option and match, and how to run programs with cargo. You have already seen how to create a Vec<T> and grow it with push. Here you will learn the two main ways to read an element back, and when to choose each.
Two ways to read one element
A Vec<T> gives you two ways to read the element at a position:
v[i]is indexing. It returns the element itself (as a place expression), and it panics ifiis out of range.v.get(i)returnsOption<&T>. It givesSome(&element)wheniis in range andNonewhen it is not.
fn main() {
let scores = vec![90, 72, 85];
let a = scores[1]; // i32, copied out of the Vec
let b = scores.get(1); // Option<&i32>
let c = scores.get(10); // None
println!("{a} {:?} {:?}", b, c); // 72 Some(72) None
}Indices are usize values that start at 0. A Vec of length 3 has valid indices 0, 1 and 2. An index of 3 is already out of range.
What a panic means
A panic is Rust's way of stopping the current thread when the program reaches a state it cannot continue from. By default it prints a message and unwinds the stack. In a single-threaded program, that ends the process with a non-zero exit code.
fn main() {
let v = vec![1, 2, 3];
let i = 7;
println!("{}", v[i]);
}Running this prints a message like:
thread 'main' panicked at src/main.rs:4:20:
index out of bounds: the len is 3 but the index is 7The check is always on. It runs in release builds as well as debug builds. Rust does not read memory past the end of the buffer, so you get a clean crash rather than undefined behavior. That safety has a small cost: each index operation compares the index with the length.
flowchart TD
A[Read position i] --> B{i < v.len?}
B -- yes --> C[Return element]
B -- no, using v i --> D[Panic]
B -- no, using v.get i --> E[Return None]The diagram above is not valid in the format required, so see the corrected version below.
Choosing between them
Use indexing when an out-of-range index would mean your program has a bug. Use get when the index comes from data you do not control, or when "no such element" is a normal outcome.
| Situation | Better choice | Reason |
|---|---|---|
| Loop counter you computed from `v.len()` | `v[i]` | The index is valid by construction. |
| Index typed by a user or read from a file | `get(i)` | Bad input should not crash the program. |
| Looking at the first or last item | `first()` / `last()` | They return `Option` and say what you mean. |
| Test code that asserts a known layout | `v[i]` | A panic is a clear test failure. |
A panic is not always wrong. Some code treats an invalid index as a broken invariant, and a loud failure is the right result. The mistake is using indexing on untrusted input and then being surprised when the program crashes.
Handling the Option from get
Because get returns an Option, the compiler forces you to deal with the missing case. You can use match, if let, or an Option method.
fn main() {
let scores = vec![90, 72, 85];
match scores.get(5) {
Some(s) => println!("score {s}"),
None => println!("no score at that position"),
}
if let Some(s) = scores.get(0) {
println!("first score {s}");
}
let third = scores.get(2).copied().unwrap_or(0);
let tenth = scores.get(9).copied().unwrap_or(0);
println!("{third} {tenth}"); // 85 0
}get yields Option<&i32>, a reference. The copied() method turns Option<&i32> into Option<i32> for types that implement Copy. For types that do not, such as String, use cloned() if you need an owned value, or keep the reference.
The first and last methods are shortcuts for the two most common positions:
fn main() {
let v = vec![4, 9, 2];
println!("{:?} {:?}", v.first(), v.last()); // Some(4) Some(2)
let empty: Vec<i32> = Vec::new();
println!("{:?}", empty.first()); // None
}Writing v[v.len() - 1] to get the last item is a classic bug. On an empty Vec, v.len() - 1 underflows a usize. That panics in debug builds and wraps to a huge number in release builds, which then fails the bounds check. v.last() avoids the problem.
Indexing with ranges
Indexing also accepts ranges, and the result is a slice rather than a single element. A range that goes past the end, or one whose start is greater than its end, also panics. get accepts ranges too, and returns None instead.
fn main() {
let v = vec![10, 20, 30, 40];
println!("{:?}", &v[1..3]); // [20, 30]
println!("{:?}", v.get(1..3)); // Some([20, 30])
println!("{:?}", v.get(2..9)); // None
// &v[2..9] would panic
}Slices are covered in detail in a later chapter. For now, note that the same panic-or-Option choice applies.
Mutating through an index or get
Indexing is a place expression, so you can assign to it directly when the Vec is mutable. get_mut is the Option-returning counterpart and gives Option<&mut T>.
fn main() {
let mut v = vec![1, 2, 3];
v[0] = 100;
if let Some(x) = v.get_mut(2) {
*x += 10;
}
match v.get_mut(8) {
Some(x) => *x = 0,
None => println!("index 8 does not exist"),
}
println!("{:?}", v); // [100, 2, 13]
}Note that v[8] = 0 would panic. Also note that indexing cannot add an element. To grow a Vec, use push or insert.
Common errors
- Indexing with the wrong type. Indices must be
usize. Writingv[i]whereiis ani32is a compile error. Convert withi as usizeonly after checking thatiis not negative, or useusize::try_from(i). - Moving a non-
Copyelement out by indexing.let s = names[0];on aVec<String>fails to compile with "cannot move out of index". Borrow with&names[0], copy withnames[0].clone(), or useget(0). - Off-by-one on
len().v[v.len()]is always out of range. The last valid index islen() - 1. - Using
unwrap()ongeteverywhere.v.get(i).unwrap()panics just likev[i], with a less helpful message. If you want a panic, index. If you do not, handle theNone. - Holding the reference too long. Both
&v[0]andv.get(0)borrow theVec. The borrow lasts as long as the reference is used, and it blocks later changes to theVec. The next chapter in this series covers this in depth.
The second error is worth seeing in code:
fn main() {
let names = vec![String::from("Ana"), String::from("Bo")];
let first_ref = &names[0]; // borrow
let first_copy = names[1].clone(); // owned copy
let maybe = names.get(5); // None
println!("{first_ref} {first_copy} {:?}", maybe);
}Indexing and `Copy` values
When the element type is Copy, as with i32, v[i] copies the value out. The result is an ordinary i32 with no link back to the Vec. When the element type is not Copy, v[i] names a place inside the Vec, so you must borrow it with & or &mut. Method calls such as names[0].len() borrow automatically, so they work without an explicit &.
fn main() {
let names = vec![String::from("Ana"), String::from("Bo")];
println!("{}", names[0].len()); // 3
}Exercise
A function receives a &Vec<i32> and a usize position typed by a user. It must print the value at that position, or print "not found" when the position is out of range, without ever panicking. Which method do you use, and how do you write the function?
Show answer
Use get, because it returns None for an out-of-range position instead of panicking.
fn show(v: &Vec<i32>, pos: usize) {
match v.get(pos) {
Some(n) => println!("{n}"),
None => println!("not found"),
}
}
Exercise
Why does let s = names[0]; fail for a Vec<String>, while let n = nums[0]; works for a Vec<i32>? Give two ways to fix the String case.
Show answer
String is not Copy, so reading names[0] would move the string out of the Vec and leave a hole in it. i32 is Copy, so the value is copied. Fix it by borrowing (let s = &names[0];) or by cloning (let s = names[0].clone();). Using names.get(0) also works and gives an Option<&String>.