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 is a fixed-length sequence whose elements can have different types. Access elements by zero-based position, or destructure them into separate bindings. Tuples are useful for returning multiple values from a function. section 4.5.2

Return values in a tuple

fn swap<A, B>(a: A, b: B) -> (B, A) { (b, a) } let tuple = swap(1, 2); println!("{}, {}", tuple.0, tuple.1); let (first, second) = tuple; section 4.5.2

A match pattern can also destructure a tuple. Unlike arrays, tuples cannot be sliced or iterated over, and their component types cannot be determined at run time. Avoid tuples longer than 12 elements: there is no strict length limit, but the standard library provides trait implementations only up to that size. section 4.5.2

A tuple struct is a distinct form of struct with unnamed, typed fields accessed by position. Omitting field names can be convenient, but may make their meaning ambiguous; use named fields when clarity matters. section 4.5.3

How Code Like a Pro in Rust covers it

How deep it goes
Explains positional access, destructuring, and limitations, while deferring detailed pattern matching.
Examples
Demonstrates a generic swap function, positional access, destructuring, and a tuple struct containing a String.
What you can do after
Apply tuples to return and unpack multiple values, while recognizing their limitations and the ambiguity of unnamed fields.
How it connects
Connects tuples to arrays, pattern matching, trait implementations, and tuple structs.

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.