Beginner · Types, control flow and functions · topic 6 of 50 · 20 min
Compound types: tuples and arrays
Explanation
Why compound types?
Often one value is not enough. A train has a number and a name; a week has seven temperatures. A compound type groups several values into one. Rust has two built-in ones: the tuple and the array. Later you will meet structs (named groups) and Vec (a list that can grow).
Tuples
A tuple is a fixed-size group of values that can have different types. You write it with round brackets. Its type lists each part's type.
fn main() {
let train: (u32, &str, f32) = (12951, "Mumbai Rajdhani", 15.5);
println!("{} {}", train.0, train.1); // by position, starting at 0
let (number, name, hours) = train; // destructuring
println!("{name} ({number}) takes {hours} hours");
}Destructuring means unpacking the parts of a value into separate variables in one line. You can ignore a part with an underscore: let (number, _, _) = train;.
The unit type ()
A tuple with no values, written (), is called the unit type. It means "nothing useful". A function that returns nothing actually returns (). You will see it in error messages like "expected i32, found ()".
Arrays
An array holds a fixed number of values that all have the same type. Its type is written [type; length]. The length is part of the type, so [i32; 3] and [i32; 4] are different types. Arrays live on the stack, which makes them fast (module 3 explains the stack).
fn main() {
let temps: [i32; 7] = [31, 33, 30, 29, 34, 35, 32];
let zeros = [0; 5]; // [0, 0, 0, 0, 0]
println!("Monday: {}", temps[0]);
println!("Days: {}", temps.len());
println!("{:?}", zeros);
for t in temps {
print!("{t} ");
}
println!();
}Out of bounds
let marks = [78, 85, 91];
let i = 5;
println!("{}", marks[i]);
// thread 'main' panicked: index out of bounds: the len is 3 but the index is 5If the index is a literal number the compiler can see, it may even refuse to compile. For indexes that come from users, use marks.get(i), which returns Some(value) or None instead of crashing (see module 5).
Arrays or Vec?
| Array [T; N] | Vec<T> (module 6) | |
|---|---|---|
| Size | Fixed, known at compile time | Can grow and shrink |
| Where stored | Stack (or inside another value) | Items on the heap |
| Good for | Days of the week, RGB colours, a 3x3 board | Lists from files, users or the network |
Common mistakes
- Writing temps[7] for the 7th item. Indexes start at 0, so the last of 7 items is temps[6].
- Expecting an array to grow with push. Arrays are fixed; use a Vec.
- Using {} to print an array or tuple. They have no Display format; use {:?}.
- Mixing types in an array, like [1, "two"]. All items must have the same type; use a tuple or a struct instead.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Compound types: tuples and arrays · 1/7
Compound types group several values into one. Rust has two built in: tuples and arrays.
Prefer a video by a teacher? Find free videos on “rust tuples arrays tutorial beginners” on YouTube ↗
In real life: A weekly sales report
A tea stall owner records cups sold each day of the week. The week always has 7 days, so an array [u32; 7] fits perfectly. The day with the most sales is returned as a tuple (day_index, cups) so the caller gets both values at once.
fn main() {
let cups: [u32; 7] = [120, 95, 110, 130, 160, 210, 190];
let mut best = (0, cups[0]);
for (day, &count) in cups.iter().enumerate() {
if count > best.1 {
best = (day, count);
}
}
println!("Best day: {} with {} cups", best.0, best.1);
}Practice (0/3 done)
let p = ("Asha", 21, 'B'); What is p.2?
What happens here? let a = [1, 2, 3]; let i = a.len(); println!("{}", a[i]);
Store the marks of one student in 5 subjects in an array. Print the total, the average (as f64) and the highest mark. Return name and total together as a tuple and print it with {:?}.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Functions, statements and expressionsTypes, control flow and functions · same module
- Control flow: if, loop, while and forTypes, control flow and functions · same module
- Tuples: fixed groups of valuesPython Programming · Lists, tuples, dictionaries and sets
- Copy and CloneOwnership: Rust's big idea
- Vec<T>: growable listsError handling and collections
- Basic types and inferenceJavaScript Programming (language in depth) · TypeScript basics
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
Which is a valid array type for five f64 values?
Answer: [f64; 5]
Array types are written [type; length].
What does [7; 3] create?
Answer: [7, 7, 7]
[value; count] repeats value count times.
Which format prints a whole tuple?
Answer: {:?}
Tuples and arrays implement Debug, so use {:?}.
What is the unit type?
Answer: The empty tuple (), meaning no useful value
Functions without a return value return the unit type ().
Which of these is a tuple?Related
Answer: (1, 2)
Round brackets with commas make a tuple. Square brackets make a list, and curly braces make a set.
Is (i32, f64, bool) Copy?Related
Answer: Yes, because every part is Copy
A tuple is Copy when all of its parts are Copy.
From Copy and Clone
What type must an index be?Related
How do you write "an array of strings"?Related
Answer: string[]
string[] (or Array<string>) is an array of strings. [string] is a tuple of exactly one.
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 3 more topics in “Types, control flow and functions” before its exam: Functions, statements and expressions, Control flow: if, loop, while and for, Mini project: reading input from the user.
- Module 2 exam: Types, control flow and functions · 13 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Ownership: Rust's big idea. 50 topics left in the course before the final exam.