Skip to main content

How to Get an Element from a Vec by Its Index in Rust

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

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​

Syntax
vector[index]
vector.get(index)
PartWhat it does
vectorThe Vec to read from.
indexThe 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​

Terminal
cargo new demo
cd demo
Output
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:

src/main.rs, which makes a Vec of red, green and blue, prints the elements at positions 0 and 2, the result of get for position 5 and the length, then the element at position 3.

src/main.rs
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 a Vec of three string slices, at positions 0, 1 and 2.
  • colors[0] and colors[2] are the first and the last.
  • colors.get(5) returns an Option, which {:?} prints.
  • colors.len() is the number of elements.
  • i is used as an index, so Rust makes it a usize. Its value, 3, is one past the last position.

Step 3: Run It​

Terminal
cargo run -q
Output
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

A zsh terminal where cargo run -q prints red, blue, None and 3, then reports that thread main panicked at src/main.rs line 10 because the index is out of bounds: the len is 3 but the index is 3.

cargo run compiles the program and runs it, and -q hides Cargo's own status lines.

What Happened​

  • colors[0] printed red and colors[2] printed blue.
  • colors.get(5) returned None: there's no position 5, and get said so without stopping the program.
  • colors.len() printed 3.
  • colors[i] with i at 3 panicked: "index out of bounds: the len is 3 but the index is 3". The program stopped there, on line 10 of src/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​

MistakeWhat happensDo this instead
Counting from 1The first element is at 0: colors[2] printed the third colour, blueStart counting at 0
An index equal to the lengthindex out of bounds: the len is 3 but the index is 3The last position is len() - 1; colors.last() gave Some("blue")
An i32 variable as the indexerror[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​

SymptomLikely causeFix
index out of bounds: the len is 3 but the index is 3The index is past the last elementCheck it against len(), or use get
the type `[&str]` cannot be indexed by `i32` The index isn't a usizelet 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​