liveBook · Manning

Tuple

As explained in Code Like a Pro in Rust

A tuple is a fixed-size heterogeneous sequence whose element types are specified positionally.

A Rust tuple groups a fixed number of values whose types may differ by position. It is a compound primitive type, useful when a small set of values belongs together without a named data structure. section 4.5.2 section 4.5.1

Choose the access pattern that fits the job:

  • Use zero-based positional fields for direct access: `tuple.0`, `tuple.1`, and so on. section 4.5.2
  • Use `let (a, b) = tuple` to destructure its values; this moves values out of the tuple. A `match` pattern can destructure them temporarily. section 4.5.2

Return two values without a wrapper type

`fn swap<A, B>(a: A, b: B) -> (B, A) { (b, a) }` returns both inputs in reversed positions. The return type records the type of each position, even when `A` and `B` differ. section 4.5.2

Do not treat a tuple as an array: tuples cannot be iterated, sliced, or inspected for component types at run time. For a named type with positional fields, a tuple struct is an option, but omitting field names can make its meaning ambiguous. Keep tuples modest in length: there is no strict maximum, but the standard library provides trait implementations only through 12 elements. section 4.5.2 section 4.5.3

How Code Like a Pro in Rust covers it

How deep it goes
Defines tuple shape and demonstrates access, destructuring, and return values; defers detailed pattern matching.
Examples
Shows positional printing, `match` and `let` destructuring, and a generic `swap` function returning `(B, A)`.
What it assumes
Assumes basic Rust syntax, demonstrates tuple operations directly, and defers detailed pattern matching.
What you can do after
Apply tuples to small positional groups and multiple return values while avoiding array-like operations and oversized tuples.
How it connects
Contrasts tuples with arrays and tuple structs, and connects destructuring to pattern matching.

Also explained in

Compare how 15 books explain tuple →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Code Like a Pro in Rust. The section links point to the parts of the book it draws on.