Storing Lists of Values with Vectors

In this chapter, we'll explore use vectors to store variable-length lists of values.

Storing Lists of Values with Vectors

The Vec<T> type, or vector, lets you store more than one value in a single data structure with all values next to each other in memory. Vectors can only store values of the same type.

Creating a Vector

Create an empty vector:

let v: Vec<int> = Vec::new()

More commonly, initialize directly with values:

let v: Vec<int> = [1, 2, 3]

Updating a Vector

Add elements with push:

let mut v: Vec<int> = Vec::new()
 
v.push(5)
v.push(6)
v.push(7)

Reading Elements

Access elements by indexing or with get:

let v: Vec<int> = [1, 2, 3, 4, 5]
 
let third = v[2]           // Direct access (panics if out of bounds)
let third = v.get(2)       // Returns Option<int>

Using get is safer:

let v: Vec<int> = [1, 2, 3, 4, 5]
 
match v.get(100) {
    Some(x) => println("Element: ", x)
    None => println("No element at that index")
}

Iterating Over Vectors

let v: Vec<int> = [100, 32, 57]
 
for i in v {
    println(i)
}

Mutate elements while iterating:

let mut v: Vec<int> = [100, 32, 57]
 
for mut i in v {
    i = i + 50
}

Common Vector Methods

let mut v: Vec<int> = [1, 2, 3]
 
v.push(4)           // Add to end
let last = v.pop()  // Remove from end, returns Option
v.insert(0, 0)      // Insert at index
v.remove(1)         // Remove at index
let len = v.len()   // Get length
let empty = v.is_empty()  // Check if empty

Continue to Strings.