profileRyan KesPGP keyI build stuffEmailGithubTwitterLast.fmMastodonMatrix

Rust Vectors

Traits

std

convert

Description

Vectors allow you to store more than one value in a single data structure that puts all the values next to each other in memory. Vectors can only store values of the same type. They are useful when you have a list of items, such as the lines of text in a file or the prices of items in a shopping cart.

Creating a New Vector

fn main() {
    let v: Vec<i32> = Vec::new();
}

vec! macro

Rust can often infer the type of value you want to store in the Vector. For convenience one can also use the vec! macro.

fn main() {
    let v = vec![1, 2, 3];
}

Updating a Vector

fn main() {
    let mut v = Vec::new();

    v.push(5);
    v.push(6);
    v.push(7);
    v.push(8);
}

Dropping a Vector

Like other structs, vectors are freed when they go out of scope, along with the vector contents:

fn main() {
    {
        let v = vec![1, 2, 3, 4];

        // do stuff with v
    } // <- v goes out of scope and is freed here
}

Read Vector elements

There are two ways to reference a value stored in a vector:

fn main() {
    let v = vec![1, 2, 3, 4, 5];

    let third: &i32 = &v[2];
    println!("The third element is {}", third);

    match v.get(2) {
        Some(third) => println!("The third element is {}", third),
        None => println!("There is no third element."),
    }
}

Using get together with match seems preferable, as trying to get non existant elements with method #1 will cause an `index out of bounds` panic:

fn main() {
    let v = vec![1, 2, 3, 4, 5];

    let does_not_exist = &v[100];
    let does_not_exist = v.get(100);
}

When the get method is passed an index that is outside the vector, it returns None without panicking.

Iteration

Immutable references

fn main() {
    let v = vec![100, 32, 57];
    for i in &v {
        println!("{}", i);
    }
}

Mutable references

fn main() {
    let mut v = vec![100, 32, 57];
    for i in &mut v {
        *i += 50;
    }
}

Using Enums to store multiple types

fn main() {
    enum SpreadsheetCell {
        Int(i32),
        Float(f64),
        Text(String),
    }

    let row = vec![
        SpreadsheetCell::Int(3),
        SpreadsheetCell::Text(String::from("blue")),
        SpreadsheetCell::Float(10.12),
    ];
}

Related