Sub topic 2
Reading elements: indexing vs get
This chapter assumes you know basic Rust syntax, ownership and borrowing, Option and match, and how to run programs with cargo. It covers the two ways to read one element from a Vec<T>. They differ in how they handle a position that does not exist.
Two ways to read
Indexing uses square brackets: v[2]. The get method takes a position and returns an Option<&T>.
fn main() {
let mut scores: Vec<i32> = Vec::new();
scores.push(90);
scores.push(72);
let primes = vec![2, 3, 5, 7];
println!("{:?}", scores.get(1)); // Some(72)
println!("{:?}", scores.get(5)); // None
println!("{}", primes[2]); // 5
println!("{:?}", scores.pop()); // Some(72)
}scores.get(5) returns None because the Vec has only two elements. Nothing crashes. The code that called get decides what to do next.
What happens when the position is out of range
Indexing with a position that does not exist makes the program panic. A panic stops the current thread and prints an error such as index out of bounds: the len is 4 but the index is 10.
fn main() {
let primes = vec![2, 3, 5, 7];
println!("{}", primes[10]); // panics at runtime
}The compiler does not reject this code. It cannot know the length of a Vec at compile time, so the check happens when the program runs.
The two forms compare like this:
| Form | Returns | Position out of range |
|---|---|---|
| `v[i]` | The element itself (a place you can read or assign to) | Panics |
| `v.get(i)` | `Option<&T>` | Returns `None` |
Positions must be of type usize. A negative number or an i32 variable will not compile as an index. Convert it first, for example with usize::try_from(n).
Choosing between them
Use indexing when a missing element would mean your program has a bug. For example, if you just built a Vec with four items and read position 2, a panic is the right response to a mistake.
Use get when the position comes from outside your code, such as user input, a file, or a calculation that could go past the end. Handle both outcomes with match:
fn main() {
let scores = vec![90, 72];
let wanted = 5;
match scores.get(wanted) {
Some(score) => println!("score: {score}"),
None => println!("no score at position {wanted}"),
}
}get also has a mutable partner, get_mut, which returns Option<&mut T>. Methods such as first and last are shortcuts for common positions and also return an Option.
Common mistakes
- Using
v[v.len()]to read the last element. The last valid position isv.len() - 1. Usev.last()instead, which is safe for empty Vecs too. - Calling
v[0]on an empty Vec. Usev.first()when the Vec might be empty. - Forgetting that
getreturns a reference inside theOption. Print it as shown above, or copy it out with.copied()for types likei32.
Exercise
A function receives a Vec<i32> and a position n: usize from a user. It must print the value, or print "missing" if there is none, without ever panicking. Which read form do you use, and how do you write it?
Show answer
Use get, because the position comes from outside the program. For example: match v.get(n) { Some(x) => println!("{x}"), None => println!("missing") }.