Sub topic 1
Tuples: grouping values of different types
A tuple is a fixed-size group of values, and each value can have a different type. This chapter covers how tuple types are written, how values are built, and what the compiler guarantees about them. Later chapters cover reading fields, destructuring, and trait support in detail.
Prerequisites
This chapter assumes you can do the following:
- Write
letbindings and simple functions, and print withprintln!. - Recognize scalar types such as
i32,f64,bool, andchar. - Read
&strand&Tas borrowed values. - Run a program with
cargo run.
What a tuple is
A tuple groups a fixed number of values into one value. You write the values in parentheses, separated by commas. The group has a type that records the type of every position.
fn main() {
let record = (42, 3.14, "hello", 'x', true);
let point: (i32, f64, &str) = (10, 2.5, "origin");
println!("{:?}", record);
println!("{:?}", point);
}The type of point is (i32, f64, &str). The type lists each element type in order, in parentheses. The first element is an i32, the second an f64, and the third a &str.
The {:?} format prints a tuple using the Debug trait. A tuple has no Display implementation, so {} does not compile for it.
The type includes every position
A tuple type is defined by its length and by the type at each position. Two tuples have the same type only if both match.
| Value | Type |
|---|---|
| `(1, 2)` | `(i32, i32)` |
| `(1, 2.0)` | `(i32, f64)` |
| `(2.0, 1)` | `(f64, i32)` |
| `(1, 2, 3)` | `(i32, i32, i32)` |
All four types are different. You cannot pass a (f64, i32) where a (i32, f64) is expected, and you cannot pass a three-element tuple where a two-element tuple is expected. The compiler reports these as type mismatches.
fn describe(pair: (i32, f64)) -> String {
format!("int={} float={}", pair.0, pair.1)
}
fn main() {
println!("{}", describe((7, 0.5)));
}Here describe accepts exactly one shape of tuple. A call such as describe((0.5, 7)) fails to compile, because the positions are in the wrong order.
How the compiler infers element types
You rarely need to write a tuple type yourself. The compiler infers each element type from the value, using the same rules as for single variables. An integer literal defaults to i32, and a float literal defaults to f64.
An annotation can override the defaults, and the literals then take the annotated types.
fn main() {
let a = (1, 2.0);
let b: (u8, f32) = (1, 2.0);
let nested = ((1, 2), ("a", "b"));
println!("{:?}", a);
println!("{:?}", b);
println!("{:?}", nested);
}The type of a is (i32, f64). The type of b is (u8, f32). Elements can themselves be tuples, so the type of nested is ((i32, i32), (&str, &str)).
A common mistake is an annotation that disagrees with a literal. In let t: (i32, f64) = (1, 2); the second literal is an integer, but the annotation asks for an f64. Rust does not convert integer literals to floats, so write 2.0.
Mutability applies to the whole tuple
A tuple binding is immutable unless you declare it with mut. With mut, you can change individual elements, but you cannot change their types.
fn main() {
let mut reading = (0, "idle");
println!("{:?}", reading);
reading.0 = 5;
reading.1 = "active";
println!("{:?}", reading);
reading = (9, "done");
println!("{:?}", reading);
}You can assign a single position, as in reading.0 = 5. You can also replace the whole tuple, as long as the new value has the same type. Assigning reading.0 = "five" fails, because position 0 has type i32. The next chapter covers the .0 syntax in detail.
Ownership and copying
A tuple owns its elements. If every element is Copy, the tuple is Copy too, and assigning it makes a copy. If any element is not Copy, such as a String, the tuple moves.
fn main() {
let a = (1, 2.5);
let b = a;
println!("{:?} {:?}", a, b);
let owned = (String::from("name"), 30);
let moved = owned;
println!("{:?}", moved);
}The first println! uses a after let b = a, which is allowed because (i32, f64) is Copy. If the last line printed owned, the program would fail with a "borrow of moved value" error. The tuple was moved because it contains a String.
When a tuple is the wrong choice
Tuples work well for short-lived groupings, such as a function's return values or a key and a value. They become hard to read when the meaning of each position is not obvious. A (f64, f64, f64) could be a position, a color, or a size.
In that case, use a struct with named fields, or a tuple struct that gives the group its own type name.
struct Rgb(u8, u8, u8);
struct Point {
x: f64,
y: f64,
}
fn main() {
let red = Rgb(255, 0, 0);
let origin = Point { x: 0.0, y: 0.0 };
let pair = (255u8, 0u8, 0u8);
println!("{} {} {}", red.0, red.1, red.2);
println!("{} {}", origin.x, origin.y);
println!("{:?}", pair);
}Rgb and a plain (u8, u8, u8) hold the same data, but they are different types. A function that takes an Rgb rejects a plain tuple, which prevents mixing up unrelated groups of three bytes.
Limits of tuples
Tuples are not collections in the way arrays and Vec are. These limits follow from how the type works:
- You cannot loop over a tuple, because its elements can have different types and a loop variable needs one type.
- You cannot index with a variable. The position in
.0must be a literal number written in the source, so the compiler knows the element's type. - You cannot add or remove elements. The length is part of the type.
- The standard library implements traits such as
Debug,PartialEq, andDefaultonly for tuples up to 12 elements. Larger tuples compile but lose these traits, which is another sign to use a struct.
If you need to repeat an operation over many values of one type, use an array, a slice, or a Vec, covered in later chapters.
Exercise
What is the type of the value (3, 4.0, "x"), and why does passing it to a function that expects (i32, f64) fail?
Show answer
The type is (i32, f64, &str). A tuple type includes its length and the type at each position, so a three-element tuple is a different type from a two-element tuple, and the compiler rejects the call with a type mismatch.
Exercise
Given let owned = (String::from("a"), 1); let moved = owned;, can you still use owned afterwards? Would the answer change for let t = (1, 2.0); let u = t;?
Show answer
No for the first case. The tuple contains a String, which is not Copy, so the whole tuple moves and owned is no longer usable. Yes for the second case. Both elements are Copy, so the tuple is Copy and t remains valid after let u = t.