2.12 Vectors

There’s anothe thing in the Rust programming language known as a vector. They’re quite similar to arrays in that they store data in an array-like structure—although rather than having a set number of elements, they vectors are mutable in size. This means that you may add and remove elements from a vector at any time you so may wish.

Creation

In order for us to create a vector, Rust has contained within it a macro that does the job for us:

let v = vec![2, 3, 4];

You might notice how we put [] around this macro rather than () like we have for all macros we have used prior to this section. This we do by convention, not because we have to—both are equally valid for Rust macros, it’s just that [] looks more like a vector and () more like a regular function.

Shorthand

Just like there’s a shorthand for creating huge arrays, with all its elements set to one value, there’s an identical shorthand for vectors:

let v = vec![0; 5];

This code creates a vector of size five, with all its five elements set to zero.

Access

Using subscript notation, no differently from the way you would access elements from a regular array, you may acces an element from a vector:

let v = vec![2, 3, 4];

println!("{}", v[0]);

But if you would like to input a let binding rather than a regular number, it wouold have to be a variable-size generic type of type usize. The above code will print 2.

Error handling

Make sure you don’t attempt to retrieve an element that is outside the vector’s boundaries, as this will cause a panic!. There's however something you can do about this, by dereferencing the error:

let v = vec![2, 3, 4];

match v.get(55)
{
    Some(x) => println!("{}", x), 
    None => println!("Out of bounds!")
}

We can use the method get in order to retrieve the element. This returns an Option that either has a value set to it, or no value at all. If it has no value set to it, it will print “Out of bounds!”

You could even make it panic! upon not locating the value, had you wanted to.

Remove, push and pop

Once again, the interesting part of vectors is that you may add and remove elements from it. It can be done very easily:

let mut v = [2, 3, 4];

v.remove(0);
v.push(3);
v.pop();

println!("{:?}", v);

This will print:

[3, 4]

Breakdown

We create a mutable vector—it needs be mutable in order for us to add and remove elements from it—containing elements by the values of two, three and four.

By calling remove with the argument 0, we remove the zeroth element—being the first element within the vector—with a value of two. The vector now contains [3, 4].

The method push adds an element onto the end of the vector. In this case, we add a three at the end of the vector that was [3, 4]—the vector now contains [3, 4, 3].

Making use of the pop method, we remove the last element inside the vector—being the value of three—the element we previously added. The vector now contains [3, 4]

We print the vector out using {:?} inside the println!. This will print out various different types of structures in a way that we can view and understand them. This is covered over the Format section.

Do make sure that you’re using a mutable vector for this, otherwise this isn’t going to work.

Exercises

  • Make a vector that contains elements one to one hundred—each number having its own unique slot within the vector in order, smallest number first.
  • Modify the vector from the previous exercise by removing numbers twenty to eighty. Print the vector out into the console and celebrate!

Moreover

Try to use arrays over vectors where possible, as vectors are slightly slower than that of a traditional array. Whenever you need to add and remove items, indulge in the beauty of vectors!

Input