Tuples

A tuple is a general-purpose static-length aggregation of types, in other words, it's a single type that consists of an aggregate of zero or more types. The internal types that make up a tuple, and the tuple's arity, define the tuple's type.

Declare

To declare a tuple we wrap the values in ().

    // Define a tuple containing 2 u64 types
    let mut balances = (42, 1337);

Retrieve by Index

Values can be retrieved individually from the tuple by specifying the index.

    // first = 42, second = 1337
    let first = balances.0;
    let second = balances.1;

Mutate

A value can be mutated in a tuple as long as the tuple is declared to be mutable and the new value has the same type as the previous value.

    // 12 has the same type as 42 (u64) therefore this is valid
    balances.0 = 12;

    // true is a Boolean and the tuple expects a u64 therefore this is invalid
    // balances.0 = true;

The entire tuple can be overwritten when it is mutable and the type for each value is the same.

    // 3 is the same type as 42 (u64) and so is 4 and 1337 therefore this is valid
    balances = (3, 4);

Destructure

Elements can be destructured from a tuple into individual variables.

    // first = 42, second = 1337
    let (first, second) = balances;

We can also ignore elements when destructuring.

    // 42 is ignored and cannot be used
    let (_, second) = balances;