How to Get an Element from a Vec by Its Index in Rust
To read one element of a Vec, put its position in square brackets, colors[0], counting from 0. When the position might not exist, use colors.get(i) instead: it returns None where square brackets would stop the program.
Syntax
vector[index]
vector.get(index)
| Part | What it does |
|---|---|
vector | The Vec to read from. |
index | The position, counting from 0. It's a usize, Rust's type for sizes and positions. |
vector[index] | The element at that position. If there's none, the program panics: it stops with an error message. |
vector.get(index) | Some with the element if the position exists, None if it doesn't. It never panics. |
The documentation for Vec: "The Vec type allows access to values by index, because it implements the Index trait." And: "However be careful: if you try to access an index which isn’t in the Vec, your software will panic!" It goes on: "Use get and get_mut if you want to check whether the index is in the Vec." The documentation for get: "If given a position, returns a reference to the element at that position or None if out of bounds."
The Example
The example makes a Vec of three colours, prints the first and the last by index, asks get for position 5, and prints the length. Then it reads position 3 with square brackets, one past the end, to show what happens.
Prerequisites
- Rust, installed with rustup, which comes with Cargo. This guide uses Rust 1.100.1.
Step 1: Create a Project
cargo new demo
cd demo
Creating binary (application) `demo` package
note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
cargo new demo creates a folder named demo with a Cargo.toml file, which describes the project, and src/main.rs, which holds the code. cd demo moves into it.
Step 2: Write the Code
Replace the contents of src/main.rs with:

fn main() {
let colors = vec!["red", "green", "blue"];
println!("{}", colors[0]);
println!("{}", colors[2]);
println!("{:?}", colors.get(5));
println!("{}", colors.len());
let i = 3;
println!("{}", colors[i]);
}
vec!["red", "green", "blue"]creates aVecof three string slices, at positions 0, 1 and 2.colors[0]andcolors[2]are the first and the last.colors.get(5)returns anOption, which{:?}prints.colors.len()is the number of elements.iis used as an index, so Rust makes it ausize. Its value, 3, is one past the last position.
Step 3: Run It
cargo run -q
red
blue
None
3
thread 'main' (1220272) panicked at src/main.rs:10:26:
index out of bounds: the len is 3 but the index is 3
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

cargo run compiles the program and runs it, and -q hides Cargo's own status lines.
What Happened
colors[0]printedredandcolors[2]printedblue.colors.get(5)returnedNone: there's no position 5, andgetsaid so without stopping the program.colors.len()printed3.colors[i]withiat 3 panicked: "index out of bounds: the len is 3 but the index is 3". The program stopped there, on line 10 ofsrc/main.rs. The number in brackets after'main'is the ID of the thread that panicked; panic messages have included it since Rust 1.91.0.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
| Counting from 1 | The first element is at 0: colors[2] printed the third colour, blue | Start counting at 0 |
| An index equal to the length | index out of bounds: the len is 3 but the index is 3 | The last position is len() - 1; colors.last() gave Some("blue") |
An i32 variable as the index | error[E0277]: the type `[&str]` cannot be indexed by `i32` | Declare the index as a usize |
A negative index, colors[-1] | error: negative integers cannot be used to index on a `Vec<&str>` | Use colors.last() for the last element |
Printing the result of get with {} | error[E0277]: `Option<&&str>` doesn't implement `std::fmt::Display` | Print it with {:?}, or handle Some and None first |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
index out of bounds: the len is 3 but the index is 3 | The index is past the last element | Check it against len(), or use get |
the type `[&str]` cannot be indexed by `i32` | The index isn't a usize | let i: usize = ... |
FAQ
Why does get return Some and not the element itself?
Because the element might not exist. get(5) on three colours returned None, and for a position that exists, Some holds the element.
Why is the type Option<&&str>?
get returns a reference to the element, and each element of this Vec is itself a reference, a &str.
How do I get the last element?
colors.last() returned Some("blue"). Like get, it returns None instead of panicking, there for an empty Vec.
Conclusion
vector[index] reads the element at a position counted from 0, and panics if there's none. vector.get(index) returns Some(element) or None, so use it whenever the position might be missing.
Additional Resources
- Vec, Indexing, get and last, in the standard library documentation.
