Next in Rust Programming Language we will be taking a look at Vectors which is a data structure in Rust. Vectors are like Lists in Python and arrays in C and JavaScript with some key differences.
Vectors
Vectors in Rust are like fixed size arrays but with much more functionality than just the fixed size arrays. In vectors we can add item, delete item, and also can move an item.
To initialize a vector we use the vec!
macro. For example:
fn main() {
let nums = vec![1, 2, 3];
}
To access the values of the vector there are two ways, using slicing or by using the get
method.
fn main() {
let nums = vec![1, 2, 3];
// Adding index number inside []
&nums[0]; // 1
// Or using a get method
nums.get(0); // 1
nums.get(2); // 3
}
To add or remove items in a vector we use push
and remove
methods. But for addin or removing items to the vec it must have to be of muteable type.
fn main() {
let mut nums = vec![1, 2, 3];
nums.push(4);
nums.push(5);
nums.push(6);
nums.remove(4); // index 4 not number 4
println!("{}", &nums[4]); // 6
}
Iterating over the members of a vector is same as in Python. Use a for loop.
for num in &nums {
println!("{}", num); // 1 2 3 4 6
}
Now vectors can only store values of the same data type. At the initialization when we defined the nums
vector we also placed values of type integer that tells the compiler that this vec will be of type integer. So now we can only values of type i32
in it. But there is a way to store values of other types in the vector and that is with the help of Enums which we learned in Day 121.
First we define an enum of name V with value of it being Int(i32)
and Float(f32)
. Then we can use this enum to store values of both int and float type in the vector.
fn main() {
enum V {
Int(i32),
Float(f32),
};
let mut nums = vec![V::Int(1), V::Float(1.1)];
}
But this thing is hard to deal with instead of a vector of a single type.