🎓 A1Learner
🔍

Rust Tuples

A tuple is a value that packs a fixed number of values into one. Positions in the tuple keep the values in order.

A tuple can mix types

Each position keeps its own type, so a number, text and a bool can sit side by side:

let rgb = (255, 128, 0);
let person = ("Ada", 36, true);
println!("{:?} {:?}", rgb, person);

Read a value with a dot

A dot and a position number read one value out — the first position is 0:

let rgb = (255, 128, 0);
println!("red = {} green = {}", rgb.0, rgb.1);

Dots, not brackets

There is no rgb[0] — tuples never use brackets:

let rgb = (255, 128, 0);
// rgb[0]  // error: tuples have no brackets
println!("first = {}", rgb.0);

Split a tuple into names

One let line can split a tuple into separate names:

let point = (3, 7);
let (x, y) = point;
println!("x = {} y = {}", x, y);

The empty tuple is the unit value

A function that returns nothing really returns (), the unit value:

fn greet() {
    println!("hi");
}
let result = greet();
println!("result = {:?}", result);

Example

fn min_max(values: &[i32]) -> (i32, i32) {
    (*values.iter().min().unwrap(), *values.iter().max().unwrap())
}
fn main() {
    let (lo, hi) = min_max(&[4, 1, 9, 2]);
    let rgb = (255, 128, 0);
    println!("min = {} max = {} green = {}", lo, hi, rgb.1);
}

Key points

  • Use a tuple to give back two or three related results from one function
  • You cannot loop over a tuple with for.
  • Its parts may all have different types.
  • A loop needs one type that fits every item.
  • Loop over an array instead — an array holds one type

In this example, min_max takes a slice of numbers. It returns one tuple with two values: the smallest and the largest. Inside, .min() and .max() each give an Option, and .unwrap() takes the value out, since the list is known to be non-empty. In main, the tuple is split into lo and hi in a single let. rgb is another tuple, and rgb.1 reads its second value, 128 — the green part of the colour.

Note

When the parts deserve real names, graduate to a struct (later in this section).

A tuple is for quick, small bundles.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

How do you read the second element of a tuple t?