collections
Storing Lists of Values with Vectors
Vector
The first collection type we'll look at is Vec<T>
, as known as a Vector. Vector allows you to store more than one value in a single data structure that puts all the values next to each other in memory.
How to use a vector
Let me explain the usage with a simple but classic instance:
//vector
fn ve() {
//create a new instance
let v: Vec<i32> = Vec::new();
//it's mote common to create a vector that has initial values
//as the compiler can infer the type i32 from the initial values,
//so we don't need the Vec<i32> annotation.
let mut v = vec![1,2,3];
//push in some values
v.push(4);
v.push(5);
//two ways to access elements in a vector with index
let third = &v[2];
match v.get(3) {
Some(third) => println!("vector third element is {}", third),
None => println!("there is no third element"),
}
/*
* differences between [] and get
* []: give us a i32 type element or &i32 type if we use &
* get: give us a Option<&T> type element
*/
//what if we access an element with an unexisted index
//let sixth = &v[5]; //panic when run the program
let six = v.get(5); //return None
/*
* iterating over the values in a vector with the for loop
*/
for i in &v {
println!("{}", i);
}
//use mutable reference
for i in &mut v {
*i += 1;//we have to use the dereference operator(*) to get to the value in i before we can use the += operator
}
//pop: removes the last element from a vector and returns it
println!("last element of the vector: {}", v.pop().unwrap());//unwrap is a Option<T> function to get the T value.
//drain: creates a draining iterator that removes the specified range in the vector and yields the removed items.
let dr: Vec<_> = v.drain(1..).collect();//collect is a function of iterator, we'll cover it later.
assert_eq!(v.len(), 1);
}
Little details:
WELCOME TO THE MACHINE