LibraryVectors

Vectors

Learn about Vectors as part of Rust Systems Programming

Understanding Vectors in Rust

Vectors are a fundamental data structure in Rust, providing a resizable array type. They are part of Rust's standard library and are crucial for managing collections of data efficiently. Unlike fixed-size arrays, vectors can grow or shrink as needed, making them highly flexible for various programming tasks.

What is a Vector?

A vector, often referred to as

code
Vec
in Rust, is a growable, heap-allocated array. It stores elements of the same type
code
T
. When you add elements to a vector and it runs out of space, Rust will allocate new, larger memory and move the existing elements to the new memory. This process is managed automatically, but understanding it helps in optimizing performance.

Vectors are dynamic arrays that can grow.

Vectors in Rust are similar to arrays but can change their size. They store elements of the same type and are managed on the heap.

Vectors are implemented as a tuple struct containing a pointer to the data on the heap, the length of the vector, and the capacity of the vector. The capacity is the amount of space allocated on the heap for the vector. When the length equals the capacity, Rust allocates new memory and moves the data. This dynamic resizing is a key feature that distinguishes vectors from fixed-size arrays.

Creating and Initializing Vectors

You can create a new, empty vector using

code
Vec::new()
or the
code
vec![]
macro. The
code
vec![]
macro is often more convenient for initializing a vector with some initial values.

What are the two primary ways to create a new vector in Rust?

Vec::new() and the vec![] macro.

Adding and Accessing Elements

Elements are added to a vector using the

code
push()
method. You can access elements by their index using square brackets
code
[]
or the
code
get()
method. Using
code
get()
is safer as it returns an
code
Option<&T>
, which handles cases where the index is out of bounds gracefully, returning
code
None
instead of panicking.

OperationMethodSafety
Add elementpush(value)Safe (may reallocate)
Access by indexvector[index]Unsafe (panics if out of bounds)
Access by index (safe)vector.get(index)Safe (returns Option<&T>)

Iterating Over Vectors

You can iterate over the elements of a vector using a

code
for
loop. Rust provides several ways to iterate: immutable references (
code
iter()
), mutable references (
code
iter_mut()
), and consuming iteration (
code
into_iter()
).

Iterating over a vector allows you to process each element. iter() provides immutable references, iter_mut() provides mutable references for modification, and into_iter() consumes the vector, yielding ownership of each element. This flexibility is key to Rust's memory safety and performance.

📚

Text-based content

Library pages focus on text content

Common Vector Operations

Vectors offer a rich set of methods for manipulation, including removing elements (

code
pop()
,
code
remove()
), checking the length (
code
len()
), and determining if the vector is empty (
code
is_empty()
). Understanding these methods is crucial for effective data management.

Remember that pop() removes and returns the last element, while remove(index) removes and returns the element at a specific index, shifting subsequent elements.

Vector Capacity vs. Length

It's important to distinguish between a vector's length and its capacity. The length is the number of elements currently in the vector, while the capacity is the total amount of space allocated on the heap. When the length reaches the capacity, the vector will reallocate memory to accommodate more elements. You can explicitly control capacity with

code
Vec::with_capacity()
to pre-allocate memory and potentially improve performance by reducing reallocations.

What is the difference between a vector's length and its capacity?

Length is the number of elements currently stored; capacity is the total allocated memory on the heap.

Learning Resources

The Rust Programming Language: Vectors(documentation)

The official Rust book provides a comprehensive overview of vectors, including creation, manipulation, and common use cases.

Rust Standard Library: Vec<T>(documentation)

Detailed API documentation for the `Vec<T>` type, listing all available methods and their signatures.

Rust by Example: Vectors(tutorial)

A practical, code-focused introduction to vectors with runnable examples demonstrating key operations.

Understanding Rust's Vec: Capacity and Reallocation(video)

A video explaining the concepts of vector capacity and how reallocation works in Rust.

Rust Collections: Vectors(video)

An introductory video covering the basics of using vectors in Rust, including common operations.

Rust Programming - Vectors(video)

A tutorial video demonstrating how to create, populate, and iterate over vectors in Rust.

Rust Vectors Explained(blog)

A blog post that breaks down Rust vectors, covering their properties and common methods with clear examples.

Mastering Rust Collections: Vectors(blog)

A tutorial article focusing on advanced vector usage and best practices in Rust.

Data Structures in Rust: Vectors(blog)

An overview of vectors as a data structure in Rust, explaining their implementation and usage.

Vector (computer science)(wikipedia)

A general explanation of what a vector is in computer science, providing context for Rust's implementation.