Introduction to Rust Vectors
In Rust, vectors are dynamic arrays that can grow or shrink in size. They are a versatile data structure commonly used to store a collection of elements. This tutorial will walk you through the basics of working with vectors in Rust, including initialization, manipulation, and common operations.
Initializing Vectors
To create a new vector in Rust, you can use the vec![]
macro or the Vec::new()
function.
// Using vec![] macro
let mut vec1 = vec![1, 2, 3];
// Using Vec::new() function
let mut vec2: Vec<i32> = Vec::new();
Adding Elements to a Vector
You can add elements to a vector using the push
method.
let mut vec = Vec::new();
vec.push(4);
vec.push(5);
vec.push(6);
Accessing Elements in a Vector
Elements in a vector can be accessed using indexing.
let vec = vec![1, 2, 3];
println!("First element: {}", vec[0]); // Output: 1
Iterating Over a Vector
You can iterate over the elements of a vector using a for
loop or iterators.
let vec = vec![1, 2, 3];
for num in &vec {
println!("{}", num);
}
Vector Operations
Vectors support various operations such as concatenation, slicing, and sorting.
let mut vec1 = vec![1, 2, 3];
let mut vec2 = vec![4, 5, 6];
// Concatenation
vec1.append(&mut vec2);
// Slicing
let slice = &vec1[1..3];
// Sorting
vec1.sort();
Conclusion
In this tutorial, you’ve learned the basics of working with vectors in Rust. Vectors are a powerful data structure that can be used in a wide range of scenarios. Experiment with vectors in your Rust projects to harness their flexibility and efficiency.