Skip to content

Tuples

Tuples are collections of elements of possibly different types. Accessing elements of a tuple is done the same way as arrays: with the indexing [] operator. However, tuples are not iterable.

Creating tuples

Create a tuple by providing a list of values between parentheses. The type of a tuple is the list of the types of its elements, also surrounded with parentheses.

boa
// manually specifying the type:
let point: (u8, u8) = (1, 2)

// with type inference:
let point = (1, 2)

Note that tuples must contain at least 2 elements (what would be the point of a tuple with a single element anyways?).

Accessing elements of tuples

Accessing the elements of a tuple can be done in two different ways:

  • With the indexing operator, []
  • With destructuring.

Accessing elements with [], the indexing operator

Use [] the same way as it is used for indexing arrays to access an element of a tuple. Note that unlike arrays, the value passed to the indexing operator must be known at compile-time:

boa
let point = (1, 2)
let x = point[0]

The following example is invalid, because x is not known at compile-time:

boa
let index = ... // let's say x was provided through the terminal
let x = point[index] // compile-time error: index is not known at compile time

Accessing elements with destructuring

Boa also allows the use of a destructuring statement to access the contents of a tuple. See the corresponding page for more information.