Sub topic 1
Tuples: Grouping Values of Different Types
Prerequisites
This chapter assumes you know basic Rust syntax (let bindings, functions, println!), scalar types such as i32, f64, bool, and char, and how to run a program with cargo run.
What a tuple is
A tuple groups a fixed number of values into one value. The values can have different types. The type is written as a comma-separated list in parentheses, for example (i32, f64, &str). The length and the type of each position are part of the tuple's type, so (i32, i32) and (i32, i32, i32) are different types.
fn main() {
let point: (i32, f64, &str) = (10, 2.5, "origin");
println!("{:?}", point);
}The {:?} format prints a tuple through the Debug trait. Tuples implement Debug when every element does.
Reading fields by index
Access a field with a dot and a literal position number, starting at 0. The index must be written directly in the source. It cannot be a variable, so the compiler always knows the type of the result.
fn main() {
let point = (10, 2.5, "origin");
println!("{}", point.0);
println!("{}", point.2);
}An index past the end, such as point.3, is a compile error, not a runtime panic.
Destructuring
A pattern on the left of let can take a tuple apart into separate variables. Use _ to ignore a field you do not need.
fn main() {
let point = (10, 2.5, "origin");
let (x, y, label) = point;
println!("{x} {y} {label}");
let (first, _, _) = point;
println!("{first}");
}The pattern must match the tuple's shape. Writing let (a, b) = point; fails to compile because point has three fields.
Returning multiple values
A function returns one value, but that value can be a tuple. This is the usual way to hand back a small group of related results. The function below returns the smallest and largest value of a slice. It wraps the pair in Option because an empty slice has neither.
fn min_max(values: &[i32]) -> Option<(i32, i32)> {
let first = *values.first()?;
let mut min = first;
let mut max = first;
for &v in &values[1..] {
if v < min {
min = v;
}
if v > max {
max = v;
}
}
Some((min, max))
}
fn main() {
if let Some((lo, hi)) = min_max(&[3, 1, 4, 1, 5]) {
println!("min={lo} max={hi}");
}
}The ? after values.first() returns None early when the slice is empty. The pattern Some((lo, hi)) destructures the Option and the tuple in one step.
Common errors
- Using a variable as an index, as in
point.i. Only literal indexes work. - Destructuring with the wrong number of names. The count must match, or you must use
..to skip the rest, as inlet (first, ..) = point;. - Forgetting the parentheses around the tuple in
Some((min, max)).Some(min, max)passes two arguments and does not compile.
Exercise
Write the type of a function parameter that takes a tuple of a char and a bool. Then say what let (c, flag) = pair; does when pair has that type.
Show answer
The type is (char, bool), for example fn show(pair: (char, bool)). The let statement destructures the tuple: c becomes the char and flag becomes the bool.