Rust Data Structures
So far most of your variables have held a single value: one number, one boolean, one string. Real programs usually work with groups of values — a list of scores, a player's name together with their level, a phone book that maps names to numbers. Rust gives you several built-in ways to group data, and choosing the right one makes your code simpler and faster.
This chapter is a quick tour. Each structure gets its own lesson afterwards, so don't worry about memorising every detail yet.
The main options
| Structure | Size | Element types | Typical use |
|---|---|---|---|
Array [T; N] |
fixed, known at compile time | all the same | the 7 days of the week, a 3×3 board |
Vector Vec<T> |
grows and shrinks | all the same | a shopping list, lines read from a file |
Tuple (A, B, C) |
fixed | can differ | returning two values from a function |
HashMap HashMap<K, V> |
grows and shrinks | keys → values | word counts, a lookup table |
| Struct | fixed set of named fields | can differ | a User with a name, email and age |
| Enum | one of several variants | can differ per variant | a Shape that is a circle or a square |
Arrays, vectors and hash maps are collections: they hold many values of one kind. Tuples, structs and enums let you combine different kinds of values into one new type.
Arrays and vectors at a glance
An array has a fixed length that is part of its type. A vector lives on the heap, so it can grow while the program runs.
fn main() {
let weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri"];
let mut todo = Vec::new();
todo.push("buy milk");
todo.push("call grandma");
println!("The week has {} working days.", weekdays.len());
println!("First day: {}", weekdays[0]);
println!("Tasks: {:?}", todo);
}The week has 5 working days.
First day: Mon
Tasks: ["buy milk", "call grandma"]
{:?} is the debug formatter. Most standard collections support it, which makes it the quickest way to look inside them.
Tuples and structs at a glance
A tuple groups a few values by position. A struct groups values by name, which is clearer once you have more than two or three of them.
struct Book {
title: String,
pages: u32,
}
fn main() {
let point = (3, -7);
println!("x = {}, y = {}", point.0, point.1);
let book = Book {
title: String::from("The Rust Way"),
pages: 312,
};
println!("'{}' has {} pages", book.title, book.pages);
}x = 3, y = -7
'The Rust Way' has 312 pages
Hash maps and enums at a glance
A HashMap stores key → value pairs, so you can look a value up by its key instead of by its position. An enum describes a value that can be exactly one of a few possibilities.
use std::collections::HashMap;
enum Light {
Red,
Yellow,
Green,
}
fn action(light: Light) -> &'static str {
match light {
Light::Red => "stop",
Light::Yellow => "slow down",
Light::Green => "go",
}
}
fn main() {
let mut capitals = HashMap::new();
capitals.insert("France", "Paris");
capitals.insert("Japan", "Tokyo");
println!("Capital of Japan: {}", capitals["Japan"]);
println!("Red light means: {}", action(Light::Red));
println!("Green light means: {}", action(Light::Green));
}Capital of Japan: Tokyo
Red light means: stop
Green light means: go
How to choose
Ask yourself a few questions:
- Do all the values have the same type? If yes, use a collection (array, vector or map). If not, use a tuple or struct.
- Do I know the count when I write the code? If yes, an array works. If the count changes at runtime, use a
Vec. - Will I look things up by a key rather than an index? Use a
HashMap. - Do the values deserve names? Prefer a struct over a tuple —
user.ageis easier to read thanuser.2. - Can the value be one of several shapes? Use an enum.
Tip: When in doubt, start with a
Vec. It is the most common collection in Rust code, and it is easy to switch later.
Ownership still applies
Every data structure owns its contents. When a vector goes out of scope, all the strings inside it are freed too. If you pass a vector to a function by value, the function takes ownership of the whole thing; pass &v instead when you only want to read it. You will see this pattern again and again in the following lessons.
fn total(prices: &Vec<u32>) -> u32 {
let mut sum = 0;
for p in prices {
sum += p;
}
sum
}
fn main() {
let prices = vec![120, 45, 300];
println!("Total: {}", total(&prices));
println!("Still usable: {:?}", prices);
}Total: 465
Still usable: [120, 45, 300]
Test yourself
You need a list of items whose length changes while the program runs. Which structure fits best?
- Array
- Tuple
- Vec
- Enum
Which structure lets you group values of different types under field names?
- Struct
- Array
- Vec
- HashMap
What does {:?} do inside println!?
- Prints the type name
- Prints the value using its Debug format
- Asks the user for input
- Prints only if the value exists