A vector is a growable array, meaning the new elements can be inserted at the runtime. Multiple values of the same type can be stored in a vector. In Rust, it is denoted by Vec<T>
, where T
is the vector’s type.
let my_vector1 = vec![20,40,60,80];
In the declaration above, a vector my_vector1
is created using a vector macro vec!
. Since the vector macro contains integer values, Rust automatically infers that the type of my_vector1
is Vec<i32>
.
Rust also gives us one more way to create a vector. Instead of using the vec!
macro, we can use the Vec::new()
function to create a new vector, as shown below:
let mut my_vector2 : Vec<i64> = Vec::new();
In the declaration above, my_vector2
is an i64
type mutable vector created with the Vec::new()
function.
Note: If the variable is to be modified, it must be declared as mutable.
fn main() {// Method 1 using vec! macro// storing some random values in my_vector1let my_vector1 = vec![20,40,60,80];print!("my_vector1 : ");for i in my_vector1{print!("{} ",i);}// Method 2 using Vec::new() Function//initializing my_vector2 that will contain the 64-bit integer datatypelet mut my_vector2: Vec<i64> = Vec::new();my_vector2.push(4); // inserting 4 in vectormy_vector2.push(7); // inserting 7 in vectormy_vector2.push(15); // inserting 15 in vectorprint!("\nAfter insertion in my_vector2 = ");println!("{:?}", my_vector2);my_vector2.pop(); // removing 15 from vectorprint!("After removing last value from my_vector2 = ");println!("{:?}", my_vector2);}
Line 6: We create and initialize my_vector1
with some values using the vec!
macro method.
Lines 8–12: We print the values of my_vector1
.
Line 17: We create mutable my_vector2
that will contain the 64-bit integer datatype, using the Vec::new()
function.
Lines 19–21: We insert values in my_vector2
using the push()
function.
Lines 23–24: We print the values of my_vector2
after inserting values in it.
Line 25: We remove value from my_vector2
using the pop()
function.
Lines 26–27: We print the values of my_vector2
after removing the last value from the vector.
Free Resources