Tuples
A tuple holds a fixed number of values, two or more, that may have different types. Its type lists theirs in parentheses, and a value is written the same way:
(str, int) entry = ("apples", 3)
print(entry.0, entry.1) // apples 3
print(entry) // (apples, 3)
func divmod(int a, int b) (int, int) do
return (a / b, a % b)
endentry.0 is the first item, entry.1 the second, and so on; a position
past the last is a compile error. A tuple cannot change, and is never
null. Tuples work as function parameters and results, array and map
elements, struct fields, and the values enum members carry, and with the
type parameters of generic functions, as in func swap[A, B]((A, B) pair) (B, A). The item types of a tuple written in the code come from the type
expected there, as for (i64, f64) p = (1, 2), or else from the values.
A declaration can take a tuple apart, giving each item a variable, and _
leaves an item out:
(int quotient, int remainder) = divmod(17, 5)
(str name, _) = entrySo can a loop over a collection of tuples, with or without the index or key:
(str, int)[] people = [("ana", 31), ("luis", 27)]
for (name, age) in people do
print(name, age)
end
for i, (name, age) in people do
print(i, name)
end== and != compare two tuples of the same type item by item: numbers,
characters, strings, and plain enums by value, tuples in the same way, and
other references by identity. Tuples holding enums whose members carry
values, or functions, cannot be compared. print and to_str show a tuple
as its items in parentheses, as in (apples, 3), when every item can be
printed. A tuple cannot be a map key.
Match takes tuples apart too.