Data Structures

Rust Vectors

Working with Vectors

Rust vectors are dynamic arrays with push and pop methods.

What are Rust Vectors?

Rust vectors are a part of Rust's standard library and are similar to arrays but with a key difference: they are dynamic. This means they can grow or shrink in size as needed, making them versatile for various programming scenarios.

Vectors in Rust are defined in the std::vec module and are essentially heap-allocated, contiguous sequences of elements of the same type.

Creating a Vector

To create a vector in Rust, you can use the Vec::new() method or the vec! macro, which is more commonly used for its simplicity.

Here’s how you can create a vector:

Adding Elements to a Vector

Adding elements to a vector is straightforward with the push method. This method appends an element to the end of the vector.

Here's an example:

Removing Elements from a Vector

Rust vectors provide the pop method to remove the last element. This method returns an Option, which is None if the vector is empty or Some(value) if an element is successfully removed.

Example:

Accessing Vector Elements

You can access elements in a vector using index syntax. Rust vectors provide bounds-checking, which prevents accessing indices outside the vector's current length.

Example:

Iterating Over a Vector

Vectors can be iterated over using a for loop. This allows you to perform operations on each element.

Example:

Common Vector Methods

Rust vectors come with a variety of useful methods:

  • len(): Returns the number of elements in the vector.
  • is_empty(): Checks if the vector is empty.
  • clear(): Removes all elements from the vector.
  • contains(): Checks if the vector contains a specified value.

Example of using some of these methods:

Safety and Performance

Rust vectors are designed with safety in mind. They prevent errors such as buffer overflow by ensuring that all operations are bounds-checked. Moreover, since they are implemented as contiguous blocks of memory, they offer good cache performance.

However, keep in mind that frequent resizing of vectors can lead to performance issues. It's often a good idea to pre-allocate the expected size of the vector using with_capacity if the size is known beforehand.

Previous
Slices