Skip to content
GitHub
ReferenceTuples

Tuples

Fixed groups of values by position - literals, .0, destructuring, and tuples as parameters and results.

All 2 examples tested by CIEdit this pageReport a problem

A tuple groups two or more values by position. Its type lists theirs: (i32, str).

Tested
fn min_max(xs: [i32; 4]) -> (i32, i32) {
var lo = xs[0]
var hi = xs[0]
for x in xs {
lo = lo.min(x)
hi = hi.max(x)
}
return (lo, hi)
}
fn main() {
let (lo, hi) = min_max([4, -2, 9, 3])
println("{lo} {hi}")
let t = (1, 2.5, true)
println("{t.0} {t.1} {t.2}")
var p = (0, 0)
p.1 = 5
println("{p.0} {p.1}")
}
  • (a, b, ...) builds one, running its parts left to right. A tuple has at least two parts: (x) is just x in parentheses, and () is the unit value.
  • t.0, t.1 and so on read a part. On a var they can be assigned.
  • Tuples are values, copied when assigned, like structs.
  • Tuples compare with == part by part, and print as (1, a, true) (comparing and printing). match sees inside them.

A tuple pattern takes a tuple apart. It works in let, var, for, match and if let (patterns), and _ skips a part:

Tested
fn main() {
let ((a, _), c) = ((1, 2), 3)
var (x, y) = (1, 2) // `var` makes each name a variable
x += a
y *= c
println("{x} {y}")
for (i, ch) in [(1, 'a'), (2, 'b')] {
print("{i}{ch};")
}
println()
}

A tuple in C is a struct with one field per part, so it costs what the separate values would.