What is a vector in Rust?

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.

Syntax

let my_vector1 = vec![20,40,60,80];
Declaring a vector using vec!

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();
Declaring a mutable vector using 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.

Code example

fn main() {
// Method 1 using vec! macro
// storing some random values in my_vector1
let 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 datatype
let mut my_vector2: Vec<i64> = Vec::new();
my_vector2.push(4); // inserting 4 in vector
my_vector2.push(7); // inserting 7 in vector
my_vector2.push(15); // inserting 15 in vector
print!("\nAfter insertion in my_vector2 = ");
println!("{:?}", my_vector2);
my_vector2.pop(); // removing 15 from vector
print!("After removing last value from my_vector2 = ");
println!("{:?}", my_vector2);
}

Explanation

  • 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

Copyright ©2025 Educative, Inc. All rights reserved