The Rust Programming Language — Vectors — Vectors
Arrays of Rust on Steroids!
We’ve already learnt about arrays in Rust here. Arrays in Rust can be declared like below:
fn main() {
let mut years: [i32; 3] = [2021, 2022, 2023];
}These arrays are a fixed length arrays, even though we’ve added mut keyword. mut keyword allows you to modify the values inside the array i.e. 2021, 2022 and 2023 but does not allow you to .push() or .pop() any elements from the array. The length of the array remains the same throughout the program’s lifecycle.
But, just as other programming languages, we do have need of flexible size arrays. Vector comes to the rescue. Vectors are array but with flexibility of size during program’s runtime.
Let’s have a look at below code snippet:
fn main() {
let mut years: Vec<i32> = vec![2001, 2002, 2003, 2004, 2005];
years.push(2006);
println!("The number of years are {}", years.len());
years.push(2007);
println!("The number of years are {}", years.len());
let number_of_years: usize = years.len(); // usize = u32 or u64 depending on the system
let first_year_index: usize = 0;
let first_year: i32 = years[first_year_index];
println!("The first year is {}", first_year);
let mut nums: [u32; 3] = [1, 2, 3];
let mut nums_vec: Vec<u32> = vec![1, 2, 3];
// nums.push(4); <-- this will panic
for year in years.iter() {
println!("The year is {}", year);
}
}Observations:
- Rust has a type called
Vec.Vecstands for Vector. - Vec uses a
type parameter <i32>. This indicates that all the elements inside the vector would be of typei32. - In order to create a vector array, we use a macro
vec![]. Some macros are initiated using parenthisis()indicating that they are a function call. e.g.println!(),format!()andpanic!(). Vectors are initiated using square brackets[]. e.g.vec![]to indicate that they are an array. - You can do operations like
.push(),.pop()and.len()on a vector which does just as what it describes. But for doing.push()and.pop()the vector must be mutable. Hence, we’ve addedmutkeyword. - Lust like Arrays, Vectors can be iterated over using
.iter()keyword.
We might have question in our mind that why not use vectors always rather than array? But it is important to understand how these two are fundamentally different in the usage of memory. Arrays use the stack memory because they are of “finite”or “known” length. Vectors, on the other hand, are not of “finite” or “known” length. Hence, they cannot use the stack memory. They need to use something called heap memory.
We’ll discuss about the stack memory vs heap memory in the next article. I hope you liked this article about Rust Vectors. Please share your feedback in the comments section.
You can subscribe to my newsletter about The Rust Programming Language here. You can read about all the articles in this series here.






