Module core::prim_tuple

1.0.0 · source ·
Expand description

A finite heterogeneous sequence, (T, U, ..).

Let’s cover each of those in turn:

Tuples are finite. In other words, a tuple has a length. Here’s a tuple of length 3:

("hello", 5, 'c');
Run

‘Length’ is also sometimes called ‘arity’ here; each tuple of a different length is a different, distinct type.

Tuples are heterogeneous. This means that each element of the tuple can have a different type. In that tuple above, it has the type:

(&'static str, i32, char)
Run

Tuples are a sequence. This means that they can be accessed by position; this is called ‘tuple indexing’, and it looks like this:

let tuple = ("hello", 5, 'c');

assert_eq!(tuple.0, "hello");
assert_eq!(tuple.1, 5);
assert_eq!(tuple.2, 'c');
Run

The sequential nature of the tuple applies to its implementations of various traits. For example, in PartialOrd and Ord, the elements are compared sequentially until the first non-equal set is found.

For more about tuples, see the book.

Trait implementations

In this documentation the shorthand (T₁, T₂, …, Tₙ) is used to represent tuples of varying length. When that is used, any trait bound expressed on T applies to each element of the tuple independently. Note that this is a convenience notation to avoid repetitive documentation, not valid Rust syntax.

Due to a temporary restriction in Rust’s type system, the following traits are only implemented on tuples of arity 12 or less. In the future, this may change:

The following traits are implemented for tuples of any length. These traits have implementations that are automatically generated by the compiler, so are not limited by missing language features.

Examples

Basic usage:

let tuple = ("hello", 5, 'c');

assert_eq!(tuple.0, "hello");
Run

Tuples are often used as a return type when you want to return more than one value:

fn calculate_point() -> (i32, i32) {
    // Don't do a calculation, that's not the point of the example
    (4, 5)
}

let point = calculate_point();

assert_eq!(point.0, 4);
assert_eq!(point.1, 5);

// Combining this with patterns can be nicer.

let (x, y) = calculate_point();

assert_eq!(x, 4);
assert_eq!(y, 5);
Run

Homogenous tuples can be created from arrays of appropriate length:

let array: [u32; 3] = [1, 2, 3];
let tuple: (u32, u32, u32) = array.into();
Run