From Rust Community Wiki
Jump to navigation Jump to search

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[edit | edit source]

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[edit | edit source]

let a: (i32, i32) = (5, 3);
let b: (i32,) = (5,);
let c: () = ();

Tuples can be destructured in patterns:

fn toggle((a, b): (i32, bool)) -> (bool, i32) {
    (b, a)

let (a, b) = toggle((1, true));

The empty tuple[edit | edit source]

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[edit | edit source]

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()This links to official Rust documentation 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[edit | edit source]

Tuples are convenient to use because they automatically implement many traits up to a certain length. For example, the DebugThis links to official Rust documentation 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.