Rust Vector
In Rust, a vector is a growable collection of elements that are stored in contiguous memory. Vectors are similar to arrays, but they can grow or shrink in size dynamically, and they are allocated on the heap rather than the stack.
Here's an example of how to create and use a vector in Rust:
fn main() { let mut v = vec![1, 2, 3, 4, 5]; // create a new vector with 5 elements v.push(6); // add a new element to the vector println!("Length: {}", v.len()); // prints "Length: 6" println!("Capacity: {}", v.capacity()); // prints "Capacity: 8" for i in &v { println!("{}", i); // prints each element of the vector on a separate line } }
In this example, we're creating a new vector called v
with 5 elements using the vec!
macro. We're then adding a new element to the vector using the push
method. We're printing the length and capacity of the vector using the len
and capacity
methods, respectively. Finally, we're iterating over the vector using a for
loop and printing each element on a separate line.
One important thing to note about vectors in Rust is that they can contain elements of any type, as long as all the elements have the same type. You can also create vectors of vectors, or "nested" vectors, to store collections of collections.
fn main() { let mut matrix = vec![ vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9], ]; // create a matrix with 3 rows and 3 columns matrix.push(vec![10, 11, 12]); // add a new row to the matrix for row in &matrix { for col in row { print!("{} ", col); // print each element of the matrix } println!(""); // print a newline after each row } }
In this example, we're creating a new matrix with 3 rows and 3 columns using nested vectors. We're then adding a new row to the matrix using the push
method. Finally, we're iterating over the matrix using nested for
loops and printing each element on a separate line.