The Rust Programming Language — Vectors — Vectors
Arrays of Rust on Steroids!
3 min readOct 17, 2023
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]…