Tuples
| Tuple literals | |
| Access by .0 | |
| Destructure | |
| The unit type () |
Tuple literals
A tuple groups a fixed number of values that may have different types.
Write the values in parentheses, separated by commas.
fn main() {
let point = (10, 20);
let mixed = (42, "hello", true);
println!("{:?} {:?}", point, mixed);
}
cargo run
(10, 20) (42, hello, true)
Access by .0
Tuple fields have no names, so read them by position starting from zero.
A dot plus the index selects the matching element.
fn main() {
let point = (10, 20);
println!("{} {}", point.0, point.1);
}
cargo run
10 20
Destructure
Destructuring unpacks a tuple into separate bindings in one step.
The pattern on the left mirrors the shape on the right.
fn main() {
let point = (10, 20);
let (x, y) = point;
println!("{} {}", x, y);
}
cargo run
10 20
The unit type ()
Empty parentheses form both the empty tuple value and its type, called unit.
Functions without a return type return unit, which is why plain log calls fit the same model.
fn log() {
println!("done");
}
fn main() {
let empty: () = ();
log();
println!("{:?}", empty);
}
cargo run
done
Next: Arrays
Article author: Arthur Isaev