Rust chapters

Chapter 10 of 17

Arrays and Collections

Try this in our Rust Compiler →

Storing many values

A single variable holds one value, but most programs deal with lists of things: users, orders, scores. Rust provides a built-in collection type — usually called an array or list — that holds many values under a single name and indexes them with a number starting at 0.

let mut nums = vec![10, 20, 30];
nums.push(40);
for n in &nums {
    println!("{}", n);
}

Common operations

You will spend a lot of time looping over collections, adding items, removing items, searching for an item, sorting, and transforming each element into something else. Learn your language's standard library helpers for these tasks — they are faster and clearer than hand-written loops.

Other collection types

Beyond arrays, Rust usually offers sets (no duplicates), maps (key → value pairs) and queues / stacks. Choosing the right collection for the job makes your code shorter and your program faster.

Try it yourself

Rust Compiler
Output
Code runs on the Play with Coding execution engine — your code is saved locally for next time.