Skip to content

Beginner · Types, control flow and functions · topic 6 of 50 · 20 min

Compound types: tuples and arrays

Explanation

A tuple groups a fixed number of values of different types, like (String name, age). An array holds a fixed number of values of the same type, like [i32; 5]. You read tuple parts with .0, .1 or by destructuring, and array items with [index]. Reading past the end of an array panics at run time.

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.

rust
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");
}
Prints: 12951 Mumbai Rajdhani, then Mumbai Rajdhani (12951) takes 15.5 hours. &str is a piece of text, explained in module 4.

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).

rust
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!();
}
Indexes start at 0. [0; 5] repeats 0 five times. print! prints without a new line.

Out of bounds

output
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 5
Rust checks every index. In C this would silently read random memory; in Rust it panics safely.

If 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)
SizeFixed, known at compile timeCan grow and shrink
Where storedStack (or inside another value)Items on the heap
Good forDays of the week, RGB colours, a 3x3 boardLists 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

Tuple ( ) Array [ ]

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.

rust
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);
}
Prints: Best day: 5 with 210 cups. enumerate gives (index, item) pairs.

Practice (0/3 done)

Task 1 · Question

let p = ("Asha", 21, 'B'); What is p.2?

Task 2 · Question

What happens here? let a = [1, 2, 3]; let i = a.len(); println!("{}", a[i]);

Task 3 · Practice

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

Question 1

1.Which is a valid array type for five f64 values?

Question 2

2.What does [7; 3] create?

Question 3

3.Which format prints a whole tuple?

Question 4

4.What is the unit type?

Read more (free)

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.

From Tuples: fixed groups of values

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

Answer: usize

Indexes are usize.

From Vec<T>: growable lists

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.

From Basic types and inference

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

  1. 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.
  2. Module 2 exam: Types, control flow and functions · 13 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Ownership: Rust's big idea. 50 topics left in the course before the final exam.

← Previous: Scalar types: numbers, bool and char