Rust Vectors: Resizable Array Essentials

RustRustBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will be learning about vectors, which are re-sizable arrays in Rust that can grow or shrink at any time. A vector is represented using three parameters: a pointer to the data, length, and capacity. The capacity indicates how much memory is reserved for the vector, and when the length surpasses the capacity, the vector is reallocated with a larger capacity. We can collect iterators into vectors using the collect method, initialize vectors using the vec! macro, insert new elements at the end using the push method, and get the number of elements using the len method. We can also access elements using indexing, remove the last element using the pop method, and iterate over the vector using the iter or iter_mut methods. Additionally, there are more methods available for vectors in the std::vec module.

Note: If the lab does not specify a file name, you can use any file name you want. For example, you can use main.rs, compile and run it with rustc main.rs && ./main.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL rust(("`Rust`")) -.-> rust/BasicConceptsGroup(["`Basic Concepts`"]) rust(("`Rust`")) -.-> rust/DataTypesGroup(["`Data Types`"]) rust(("`Rust`")) -.-> rust/ControlStructuresGroup(["`Control Structures`"]) rust(("`Rust`")) -.-> rust/FunctionsandClosuresGroup(["`Functions and Closures`"]) rust(("`Rust`")) -.-> rust/MemorySafetyandManagementGroup(["`Memory Safety and Management`"]) rust(("`Rust`")) -.-> rust/DataStructuresandEnumsGroup(["`Data Structures and Enums`"]) rust(("`Rust`")) -.-> rust/AdvancedTopicsGroup(["`Advanced Topics`"]) rust/BasicConceptsGroup -.-> rust/variable_declarations("`Variable Declarations`") rust/BasicConceptsGroup -.-> rust/mutable_variables("`Mutable Variables`") rust/DataTypesGroup -.-> rust/integer_types("`Integer Types`") rust/DataTypesGroup -.-> rust/string_type("`String Type`") rust/ControlStructuresGroup -.-> rust/for_loop("`for Loop`") rust/FunctionsandClosuresGroup -.-> rust/function_syntax("`Function Syntax`") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("`Expressions and Statements`") rust/MemorySafetyandManagementGroup -.-> rust/lifetime_specifiers("`Lifetime Specifiers`") rust/DataStructuresandEnumsGroup -.-> rust/method_syntax("`Method Syntax`") rust/AdvancedTopicsGroup -.-> rust/operator_overloading("`Traits for Operator Overloading`") subgraph Lab Skills rust/variable_declarations -.-> lab-99253{{"`Rust Vectors: Resizable Array Essentials`"}} rust/mutable_variables -.-> lab-99253{{"`Rust Vectors: Resizable Array Essentials`"}} rust/integer_types -.-> lab-99253{{"`Rust Vectors: Resizable Array Essentials`"}} rust/string_type -.-> lab-99253{{"`Rust Vectors: Resizable Array Essentials`"}} rust/for_loop -.-> lab-99253{{"`Rust Vectors: Resizable Array Essentials`"}} rust/function_syntax -.-> lab-99253{{"`Rust Vectors: Resizable Array Essentials`"}} rust/expressions_statements -.-> lab-99253{{"`Rust Vectors: Resizable Array Essentials`"}} rust/lifetime_specifiers -.-> lab-99253{{"`Rust Vectors: Resizable Array Essentials`"}} rust/method_syntax -.-> lab-99253{{"`Rust Vectors: Resizable Array Essentials`"}} rust/operator_overloading -.-> lab-99253{{"`Rust Vectors: Resizable Array Essentials`"}} end

Vectors

Vectors are re-sizable arrays. Like slices, their size is not known at compile time, but they can grow or shrink at any time. A vector is represented using 3 parameters:

  • pointer to the data
  • length
  • capacity

The capacity indicates how much memory is reserved for the vector. The vector can grow as long as the length is smaller than the capacity. When this threshold needs to be surpassed, the vector is reallocated with a larger capacity.

fn main() {
    // Iterators can be collected into vectors
    let collected_iterator: Vec<i32> = (0..10).collect();
    println!("Collected (0..10) into: {:?}", collected_iterator);

    // The `vec!` macro can be used to initialize a vector
    let mut xs = vec![1i32, 2, 3];
    println!("Initial vector: {:?}", xs);

    // Insert new element at the end of the vector
    println!("Push 4 into the vector");
    xs.push(4);
    println!("Vector: {:?}", xs);

    // Error! Immutable vectors can't grow
    collected_iterator.push(0);
    // FIXME ^ Comment out this line

    // The `len` method yields the number of elements currently stored in a vector
    println!("Vector length: {}", xs.len());

    // Indexing is done using the square brackets (indexing starts at 0)
    println!("Second element: {}", xs[1]);

    // `pop` removes the last element from the vector and returns it
    println!("Pop last element: {:?}", xs.pop());

    // Out of bounds indexing yields a panic
    println!("Fourth element: {}", xs[3]);
    // FIXME ^ Comment out this line

    // `Vector`s can be easily iterated over
    println!("Contents of xs:");
    for x in xs.iter() {
        println!("> {}", x);
    }

    // A `Vector` can also be iterated over while the iteration
    // count is enumerated in a separate variable (`i`)
    for (i, x) in xs.iter().enumerate() {
        println!("In position {} we have value {}", i, x);
    }

    // Thanks to `iter_mut`, mutable `Vector`s can also be iterated
    // over in a way that allows modifying each value
    for x in xs.iter_mut() {
        *x *= 3;
    }
    println!("Updated vector: {:?}", xs);
}

More Vec methods can be found under the std::vec module

Summary

Congratulations! You have completed the Vectors lab. You can practice more labs in LabEx to improve your skills.

Other Rust Tutorials you may like