Rust Reference ยท Primitive Types
Rust tuples
Reference for Rust tuples: creating them, accessing fields with .0, destructuring, returning multiple values, comparison order, trait support and one-element tuples.
A tuple groups a fixed number of values that can have different types. Its type is written as the list of member types in parentheses, such as (i32, &str, bool). Tuples are anonymous: members have no names, only positions, so they suit short-lived groupings like returning two results from a function. When the members need names, define a struct.
let point = (3, -1); let record: (u32, &str, bool) = (7, "ann", true);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
(T1, T2, T3) // type (e1, e2, e3) // value t.0 t.1 // field access by constant index let (a, b) = t; // destructuring pattern (T,) (e,) // one-element tuple needs the trailing comma () // the unit type, an empty tuple
| Part | Description |
|---|---|
t.N |
Position N is a literal number written in the source, not a variable. t.0.1 reaches into a nested tuple. |
| Members | Any types, including references, arrays and other tuples. |
Edge cases: (5) is just the integer 5 in parentheses; write (5,) for a one-element tuple. You cannot loop over a tuple or index it with a variable.
Usage notes
- Traits: tuples implement
Debug,Clone,Copy,PartialEq,Eq,PartialOrd,Ord,HashandDefaultwhen every member does, for tuples up to 12 members. Larger tuples still exist but lack these implementations. - Ordering is lexicographic, which makes tuples handy sort keys, as in the example above.
- Copy semantics follow the members. A tuple of
Copytypes isCopy; one holding aStringmoves. - Partial moves: you can move one member out of a tuple and keep using the others.
- Hash keys: tuples of hashable members work as
HashMapkeys, a quick way to key by coordinates. - Return values: returning a tuple and destructuring it at the call site is idiomatic for two or three related values. Beyond that, a struct documents intent better.
- Collecting pairs:
(A, B)implementsExtendandFromIterator, sounzipandpartitionproduce tuples of collections. - Layout: the compiler may reorder tuple members to save padding; do not rely on the order in memory unless you use
#[repr(C)]on a struct instead.