Sub topic 2
Reading tuple fields with .0, .1, and so on
This chapter assumes you can write a tuple type and a tuple expression, such as (10, 2.5, "origin"). It also assumes you know what let mut does and what & and &mut mean. It covers reading and writing individual tuple fields by position, the rules that restrict that syntax, and the errors you are most likely to hit.
The basic syntax
A tuple field is read by writing a dot and then a number after the tuple's name. The numbering starts at zero.
fn main() {
let mut point: (i32, f64, &str) = (10, 2.5, "origin");
println!("{}", point.0);
println!("{} {} {}", point.0, point.1, point.2);
point.1 += 1.0;
point.2 = "moved";
println!("{:?}", point);
let r = &mut point.0;
*r += 5;
println!("{:?}", point);
}This prints:
10
10 2.5 origin
(10, 3.5, "moved")
(15, 3.5, "moved")Three things happen here:
point.0is an expression of typei32. The compiler knows its type from the tuple type, so no cast or check is needed.- Assigning to a field (
point.1 += 1.0) requires the binding to be declaredmut. Withoutmut, the compiler rejects the assignment. &mut point.0borrows one field. The borrow rules apply to the field, not to the whole tuple, as described below.
The following diagram shows how the indices map to field types for the tuple above.
The index must be a literal
The number after the dot is part of the syntax. It is not a value that the program computes. The compiler needs it because each field can have a different type, so the type of point.i would depend on a runtime value. That is impossible in a statically typed language.
The following do not compile:
point.iwithlet i = 1;. The compiler readsias a field name and reports that no field namediexists.point[1]. Tuples do not implement indexing with[].for field in point. A tuple is not an iterator and cannot be looped over.
If you need to select an element by a runtime index, all elements must have the same type. That is the job of an array or a Vec, which later chapters cover.
Out-of-range indices are compile errors
Because the index is a literal and the tuple's length is part of its type, the compiler checks every access. Writing point.3 on a three-field tuple fails with an error such as "no field 3 on type (i32, f64, &str)". A tuple access can never panic at run time. This is a difference from array indexing, which can panic when the index is a runtime value.
Nested tuples
When a field is itself a tuple, chain the accesses:
fn main() {
let segment = ((1, 2), (3, 4));
println!("{}", segment.1.0);
let (start, end) = segment;
println!("{}", end.1 - start.1);
}segment.1.0 first selects (3, 4), then selects its first element, 3. Current compilers parse segment.1.0 correctly. Older code sometimes writes (segment.1).0 because very old versions of Rust read 1.0 as a floating-point number. You can still add the parentheses if you find them clearer.
The second half of the example uses destructuring to give names to the fields. The next chapter covers that technique in detail.
Fields in format strings
Inline format arguments accept only plain identifiers. Writing {point.0} inside the string does not work. Pass the field as a separate argument instead:
fn main() {
let point = (10, 2.5, "origin");
println!("x = {}, y = {}", point.0, point.1);
println!("label = {label}", label = point.2);
}The second line uses a named argument. It is useful when the same field appears several times in one string.
Borrowing and moving individual fields
The compiler tracks ownership per field. This lets you move or borrow one field without affecting the others.
fn main() {
let pair = (String::from("hello"), 5);
let text = pair.0;
println!("{text} {}", pair.1);
}The line let text = pair.0; moves the String out of the tuple. This is called a partial move. Afterwards pair.0 is no longer usable. pair.1 is still readable because the move did not touch it, and i32 is Copy anyway. Using the whole pair, for example println!("{:?}", pair), would now be a compile error, because part of it has been moved out.
Borrowing works in the same way. You can hold &mut pair.0 and &mut pair.1 at the same time, because they refer to different fields:
fn main() {
let mut counts = (0u32, 0u32);
let evens = &mut counts.0;
let odds = &mut counts.1;
for n in 1..=7 {
if n % 2 == 0 {
*evens += 1;
} else {
*odds += 1;
}
}
println!("{:?}", counts);
}This prints (3, 4). The borrow checker allows both mutable borrows because it sees that the two paths do not overlap. The same split is not allowed through a function call. If you call a method on counts that takes &mut self, the whole tuple is borrowed, and the field borrows would conflict.
The same syntax on tuple structs
A tuple struct is a struct with unnamed fields, and it uses the same .0, .1 syntax:
struct Meters(f64);
struct Rgb(u8, u8, u8);
fn main() {
let height = Meters(1.82);
let color = Rgb(255, 128, 0);
println!("{} {}", height.0, color.1);
}A tuple struct is a distinct type with its own name. Meters(1.0) and a plain (f64,) are not interchangeable. The access syntax is shared, but the types are different.
Common mistakes
| Mistake | What the compiler says | Fix |
|---|---|---|
| `point.3` on a 3-field tuple | no field `3` | Use an index below the tuple's length. |
| `point[0]` | cannot index into a value of type tuple | Use `point.0`. |
| `point.i` | no field `i` | Use a literal index, or switch to an array. |
| `point.0 = x` on an immutable binding | cannot assign to field of immutable binding | Declare `let mut point`. |
| `println!("{point.0}")` | invalid format string | Pass `point.0` as an argument. |
| Using `pair` after `let s = pair.0;` | borrow of partially moved value | Clone the field, borrow it, or destructure first. |
Summary of rules
- Fields are numbered from 0 and accessed with
.N, whereNis a literal. - The compiler checks the index and the type of every access, so there is no run-time failure.
- Writing a field requires a
mutbinding. - Fields can be borrowed or moved independently, which produces partial moves.
- Nested tuples chain accesses, as in
t.1.0.
Exercise
Given let mut t = (String::from("a"), 1, (2.5, 'z'));, write one statement that sets the char to 'y', and explain why let n = 2; println!("{}", t.n); does not compile.
Show answer
The statement is t.2.1 = 'y';. Field 2 is the nested tuple (2.5, 'z'), and its field 1 is the char. The binding is mut, so the assignment is allowed. t.n does not compile because the text after the dot is read as a field name, not as the value of the variable n. A tuple field must be selected with a literal number, since each field can have a different type and the compiler has to know the result type at compile time.
Exercise
With let pair = (String::from("hi"), 5);, the line let s = pair.0; runs first. Which of println!("{}", pair.1); and println!("{:?}", pair); still compiles, and why?
Show answer
Only println!("{}", pair.1); compiles. The first line moved the String out of field 0 (a partial move), but field 1 was not moved, so it can still be read. Using the whole pair in the second statement is an error, because part of it has been moved out.