Tuples in Carbon Language – Composite Types

tuples in carbon language

A tuple in carbon language is a fixed-size collection of values that can have different types, where each value is identified by its position in the tuple.

Code Examples

Declaring a variable of type tuple

var i: (i32, i32) = (15, 16);

Here we declared i as a tuple of two 32 bit integers.

Declaring a variable of type tuple with different value type

var i: (i32, f32) = (15, 16.0);

A tuple can have different types of values. In the above example we defined a tuple of two values – 32 bit integer and 32 bit float.

Declaring variable of value tuple of expressions

var i: (i32, i32) = (3 * 5, 4 * 4);

Here (3*5, 4*4) is known as tuple of expressions.

Declaring function returning a tuple

fn TupleFunc(x: i32, y: i32) -> (i32, i32) {
  return (5 * x, 8 * y);
}

In this example we have created a function TupleFunc. This function is accepting two 32 bit integer arguments – x and y. And, the return type is a tuple of two 32 bit integers.

The function is returning a tuple of expression (5 * x, 8 * y).

How to access a tuple value?

You can access a value of a tuple using index, starting from 0 to length-1. Check this example –

fn TupleFunc(x: (i32, i32)) -> (i32, i32) {
  return (2 * x[0], 2 * x[1]);
}

Here our function is accepting a single argument x which is a tuple of two 32 bit integers. Within function body, we are accessing the values of x using x[0] and x[1].

Conclusion

We saw that a tuple in carbon can be of different value types. A typical use of tuples is to return multiple values from a function. It’s values can be accessed through positional indexes.