Vectors in Rust are dynamic, resizable arrays that store elements of the same type. They provide a flexible and efficient way to manage collections of data in Rust programs.
There are multiple ways to create vectors in Rust:
Vec::new()
method
let mut numbers: Vec<i32> = Vec::new();
vec!
macro
let fruits = vec!["apple", "banana", "cherry"];
You can add elements to a vector using the push()
method:
let mut colors = Vec::new();
colors.push("red");
colors.push("green");
colors.push("blue");
Elements in a vector can be accessed using indexing or the get()
method:
let numbers = vec![1, 2, 3, 4, 5];
let third = numbers[2]; // Indexing (panics if out of bounds)
let fourth = numbers.get(3); // Returns an Option<&T>
Vectors can be easily iterated using various methods:
let names = vec!["Alice", "Bob", "Charlie"];
// Using a for loop
for name in &names {
println!("{}", name);
}
// Using iter() method
names.iter().for_each(|name| println!("{}", name));
Rust provides numerous methods for working with vectors:
len()
: Returns the number of elementscapacity()
: Returns the current capacityis_empty()
: Checks if the vector is emptyclear()
: Removes all elementspop()
: Removes and returns the last elementTo deepen your understanding of Rust collections, explore these related topics:
Mastering vectors in Rust is crucial for efficient data manipulation and storage in your programs. They offer a powerful combination of flexibility and performance, making them an essential tool in the Rust programmer's toolkit.