Tuples in Carbon Language – Composite Types

Total
0
Shares
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

.

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like
operators in carbon language

Operators in Carbon Language

Table of Contents Hide ArithmeticBitwise & BitshiftComparisonConversionLogicalIndexingFunction CallPointerMoveConclusion We have a number of operators in Carbon language like – Arithmetic, Bitwise, BitShift, Comparison, Conversion, Logical, Indexing, function call, pointer, move…
View Post
pointers in carbon language

Pointers in Carbon Language

Pointers in Carbon language are similar to C++. The type of pointers-to-values-of-type-P is written as P*. Carbon pointers do not support pointer arithmetic. What operations are supported by Pointers in…
View Post