
Creating Vectors
There are several ways to create vectors in Rust. One straightforward method is using theVec::new() function to generate an empty vector and then adding elements with the push method:
vec! macro:
Updating Vectors
Vectors are dynamic, allowing you to modify them using methods likepush, pop, and insert:
- The
pushmethod appends an element to the end of the vector. - The
popmethod removes the last element and returns it (returningNoneif the vector is empty). - The
insertmethod adds an element at a specified index, shifting other elements to the right.
Examples
get method which returns an Option, allowing for safer access:
Iterating Over Vectors
There are various ways to iterate through a vector. You can use a simplefor loop to iterate by reference:
iter method to obtain an iterator over references to the elements:
Common Vector Methods
Length and Empty Check
You can check the size and emptiness of a vector with thelen and is_empty methods:
Checking for an Element
To verify if a vector contains a specific element, use thecontains method:
Removing Elements
Remove an element at a specific index with theremove method, which also returns the removed element:
Extending a Vector
Append elements from any iterator to the end of a vector using theextend method:
Ownership and Borrowing
Rust’s ownership and borrowing rules apply to vectors too. When a vector is assigned to a new variable, ownership is transferred (moved), and the original variable becomes invalid. For instance:Borrowing an Entire Vector in a Function
When passing a vector to a function without transferring ownership, use a reference parameter. This way, the original vector remains valid after the function call:Understanding Rust’s ownership and borrowing model is crucial when working with vectors. It helps prevent common bugs related to memory safety.