Ad space (banner)
Lesson 11 / 20

Working with vectors (Vec)

This lesson covers the vector (Vec), an array whose length you can change freely.

Vec<type> is the growable array provided by Rust's standard library. push() adds an element and len() gives you the number of elements.

The sample code creates let mut fruits: Vec<String> = Vec::new();, adds fruit with push(), and then prints every element with a for loop.

A common early stumble is forgetting mut when you need to add elements. Any operation that changes the contents of a vector (such as push) requires the variable itself to be mut.

In professional work, the basic guideline is an array for a fixed number of items and a vector for data that grows and shrinks while the program runs.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Rust directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)