In Rust, a 'Vector' (specifically `Vec<T>`) is a growable list type provided by the standard library. It allows you to store a collection of values of the same type in a contiguous block of memory. Unlike arrays, vectors are dynamic; their size can increase or decrease at runtime, meaning you don't need to know the exact number of elements at compile time.
Key characteristics of Vectors:
1. Homogeneous Data: All elements stored in a `Vec<T>` must be of the same type `T`. For example, a vector of integers can only hold integers, not a mix of integers and strings.
2. Dynamic Size: Vectors can grow or shrink as needed. You can add new elements to the end (push), remove elements, or insert elements at specific positions.
3. Heap Allocated: The data within a vector is stored on the heap, allowing it to change size without needing to move the entire vector on the stack.
4. Contiguous Memory: Elements in a vector are stored next to each other in memory, which can lead to efficient access patterns.
Common Operations with Vectors:
* Creation: Vectors can be created empty using `Vec::new()` or initialized with values using the `vec!` macro.
* Adding Elements: Use the `push()` method to append an element to the end of the vector.
* Accessing Elements: Elements can be accessed by their index using `[]` (e.g., `my_vec[0]`). This method will panic if the index is out of bounds. A safer way is to use the `get()` method, which returns an `Option<&T>` (or `Option<&mut T>`), allowing you to handle out-of-bounds access gracefully.
* Removing Elements: Methods like `pop()` (removes and returns the last element, returns `Option<T>`) or `remove()` (removes an element at a specific index) can be used.
* Iteration: You can iterate over vector elements using a `for` loop, either immutably (`for item in &my_vec`) or mutably (`for item in &mut my_vec`).
* Length: The `len()` method returns the current number of elements in the vector.
Vectors are fundamental for handling collections of data in Rust when the size isn't fixed, making them very versatile for many programming tasks.
Example Code
use std::vec;
fn main() {
// 1. Creating a new, empty vector (type annotation often inferred)
let mut numbers: Vec<i32> = Vec::new();
println!("Empty vector: {:?}", numbers);
// 2. Adding elements to the vector
numbers.push(10);
numbers.push(20);
numbers.push(30);
println!("Vector after pushes: {:?}", numbers);
// 3. Creating a vector with initial values using the vec! macro
let mut fruits = vec!["apple", "banana", "cherry"];
println!("Fruits vector: {:?}", fruits);
// 4. Accessing elements by index (unsafe if out of bounds)
let first_number = numbers[0];
println!("First number: {}", first_number);
// 5. Safely accessing elements using get() (returns an Option)
match numbers.get(1) {
Some(second) => println!("Second number: {}", second),
None => println!("Index 1 is out of bounds."),
}
// Accessing an out-of-bounds index safely
match numbers.get(5) {
Some(fifth) => println!("Fifth number: {}", fifth),
None => println!("Index 5 is out of bounds."),
}
// 6. Iterating over a vector (immutable iteration)
println!("\nIterating over numbers:");
for num in &numbers {
println!("Number: {}", num);
}
// 7. Iterating over a vector (mutable iteration)
println!("\nIterating and modifying numbers:");
for num in &mut numbers {
*num += 1; // Dereference to modify the value
}
println!("Numbers after mutable iteration: {:?}", numbers);
// 8. Removing an element from the end with pop()
let popped_fruit = fruits.pop(); // Returns Option<T>
match popped_fruit {
Some(fruit) => println!("Popped fruit: {}", fruit),
None => println!("Vector was empty."),
}
println!("Fruits after pop: {:?}", fruits);
// 9. Removing an element at a specific index with remove()
// Note: This shifts all subsequent elements to the left.
if fruits.len() > 0 {
let removed_fruit = fruits.remove(0);
println!("Removed fruit at index 0: {}", removed_fruit);
}
println!("Fruits after remove: {:?}", fruits);
// 10. Getting the length of the vector
println!("\nCurrent length of numbers: {}", numbers.len());
println!("Current length of fruits: {}", fruits.len());
}








Storing Lists of Values with Vectors