Tuple
A tuple type is a heterogeneous, ordered collection of values, which means that it can contain different types and that their order is significant. Tuples are analogous to anonymous structs.
Syntax
Tuples are always surrounded by parentheses and the contents are separated by commas. Tuples that contain exactly one element require a trailing comma, in all other cases the trailing comma is optional.
Example
let a: (i32, i32) = (5, 3);
let b: (i32,) = (5,);
let c: () = ();
fn toggle((a, b): (i32, bool)) -> (bool, i32) {
(b, a)
}
let (a, b) = toggle((1, true));
The empty tuple
The empty tuple,()
, is a zero-sized type and sometimes called unit. It is special, because it is the type of statements and the implied return type of functions that do not specify a return type:fn foo() {}
// is equivalent to
fn foo() -> () {}
println!("Hello, world!");
// is equivalent to
let _: () = println!("Hello, world!");
Usage
Tuples can be used to return multiple values from a function or match on multiple values, but that's not their only use case.
Tuples can also be used in collections, e.g. in a HashMap<i32, (String, bool)>
.
When implementing a trait, tuples can be used to accept multiple values, when the trait definition only expects a single value; for example the Iterator::enumerate()
method returns an iterator over a tuple of two values.
Tuples can be used to emulate variadic functions, by accepting a generic parameter that is implemented for tuples of different lengths.
Implementations
Tuples are convenient to use because they automatically implement many traits up to a certain length. For example, the Debug
trait is implemented for all tuples of up to 12 elements, if all their elements implement Debug
as well. The same is true for many other traits.