liveBook · Manning

Tuple

As explained in Learn Rust in a Month of Lunches

A tuple is a fixed-size Rust composite value whose elements may have different types and are accessed by position.

A tuple groups a fixed number of values in parentheses. Its values can have different types, and their positions are part of the tuple’s type. Use one when several values belong together but do not all have the same type. section 3.1.3 section 3.3

Read values by position

let details = ("cloudy", 8, 'a'); println!("{} {}", details.0, details.1); Positions start at 0. Use a dot to access an item: details.0 is "cloudy" and details.1 is 8. Unlike an array or vector, this tuple holds different types. section 3.1.3 section 3.1

You can also pull the items into separate variables: let (first, second, third) = ("one", "two", "three");. This is called destructuring. The pattern must have a place for every item; use _ for a position you do not need, as in let (_, second, third) = ("one", "two", "three");. section 3.1.3

Tuples work in match patterns, too: matching (sky, temperature) lets one arm check both values. The empty tuple, (), is called the unit type. A function that returns no other value returns (); a semicolon can make an otherwise unused expression produce that empty result. section 3.2.2 section 3.1.3

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains syntax, element types, dot access, destructuring, and the unit type without descending into implementation internals.
Examples
Uses a six-item mixed-type tuple, three-string destructuring, and a weather match on two values.
What it assumes
Assumes familiarity with basic Rust values and functions while introducing tuple syntax and the unit type.
What you can do after
Build it from scratch in Rust, access its items by position, and unpack or match its values.
How it connects
Connects tuples to arrays, vectors, structs, destructuring, and match patterns.

Also explained in

Compare how 15 books explain tuple →

Related concepts

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