Start learning free

LESSON 93 OF 348 · ARRAYS I

Vec in Rust in Rust

Lesson

A big limitation of static arrays in Rust is the fact that once the array is created, it has a fixed size.

The Vec overcomes this limitation by having variable size and allowing for elements to be added or removed.


Creation:

You declare a Vec by writing the type annotation with the element type inside <>, along with the name of the variable, and call Vec::new() to create an empty one:

let mut sandwich: Vec<String> = Vec::new();

This code creates an empty Vec named sandwich where each item is a String.


Initialization I:

You can also initialize a Vec at declaration by using the vec! macro with an opening bracket, end it with a closing bracket, and put a comma between each entry, like this:

let sandwich: Vec<&str> = vec!["peanut butter", "jelly", "bread"];

We created a Vec named sandwich which consits of 3 items: "peanut butter", "jelly" and "bread".


Initialization II:

Another way of initializing a Vec at declaration is by providing the number of elements and their initial value, like this:

let animals: Vec<&str> = vec!["cat"; 5];

We created a Vec named animals which consits of 5 "cat" items.


Assignment
Follow the Coding Tutorial and let's create some Vecs!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    Arrays in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free