All lessons

Lesson 7 of 11

Vectors and indexing

Build a growable list and check whether an item exists.

main.rs

fn main() {    let mut scores = vec![10, 20];    scores.push(30);    println!("First: {}", scores[0]);    println!("Index 2: {:?}", scores.get(2));    println!("Index 8: {:?}", scores.get(8));}

Program state

scores
Uninitialized
Step 1 of 6

The program will create a list of scores.

What’s happening

A vector stores an ordered list of values of one type. The vec! macro creates a vector from the values you supply. Use push on a mutable vector to append an item.

Indexes start at zero. Use brackets when you know the index exists. Indexing outside the vector panics. The get method returns Some with a reference to an item, or None if the index is out of bounds.

The {:?} placeholder shows the result's debug representation, so you can see the Some and None cases directly.

Read more in The Rust Book