Git repo: https://github.com/caveofprogramming/rust/
Creating Vectors
Vectors store values of the same type.
We can create an empty vector using Vec::new()
and then add items to it with push()
.
It’s also possible to initialise a vector using the vec!
macro.
Retrieving Items from Vectors
There are two ways we can get items out of a vector: using a subscript in square brackets, or using get()
.
The get()
function retrieves an Option
, and we can obtain the actual value using if let
or match
.
A key difference is that if we try to access an item that’s not in the vector, the first technique will cause the program to terminate with an error message when it runs, while the second method would give us a valid Option
, which in this case would then contain “unknown”.
Looping Over Vectors
We can loop over vectors with a for
loop.
It’s possible to modify items in vectors via the references we obtain for them from the vector, even while looping.
In this case we have to use a *
to dereference the object to be modified.
Problems with Modification
Modifying a vector requires a mutable reference, and we can’t have one of those if we’ve got an immutable reference still in scope.
Using Enums in Vectors
We can use enums to store different types of things in vectors.