Sub topic 1
Tuples: Grouping Values of Different Types
Prerequisites
This chapter assumes basic Rust syntax, scalar types, functions, references, and borrowing. You should also be able to run a Rust program with Cargo.
Grouping Values with Tuples
A tuple is a fixed-size group of values. Its elements can have different types, and the tuple's type records each element's type and position.
fn min_max(values: &[i32]) -> Option<(i32, i32)> {
let first = *values.first()?;
let mut min = first;
let mut max = first;
for &value in &values[1..] {
min = min.min(value);
max = max.max(value);
}
Some((min, max))
}
fn main() {
let point: (i32, f64, &str) = (10, 2.5, "origin");
println!("{} {} {}", point.0, point.1, point.2);
if let Some((low, high)) = min_max(&[3, 1, 4, 1, 5]) {
println!("min={low} max={high}");
}
}The tuple point contains an integer, a floating-point number, and a string slice. Tuple fields are read with a dot followed by a zero-based index: .0, .1, and so on. The index is part of the source code, so invalid indexes are rejected by the compiler.
Destructuring Tuples
Destructuring assigns tuple elements to separate variables using a pattern:
let point = (10, 2.5, "origin");
let (x, y, label) = point;
println!("{x} {y} {label}");The pattern must match the tuple's shape. You can ignore an element with _:
let (x, _, label) = point;This is useful when a function returns related values that callers commonly use together.
Unit and One-Element Tuples
The unit type is (). It has exactly one value, also written (). A function that does not return a useful value returns unit implicitly.
A one-element tuple is different: its type is (T,), with a trailing comma.
let nothing: () = ();
let single: (i32,) = (42,);The comma distinguishes a tuple from ordinary parentheses.
Exercise
What is the type of (true,), and how is it different from (true)?
Show answer
(true,) has type (bool,), a one-element tuple. (true) has type bool.