🎓 A1Learner
🔍
0 of 142 lessons completed

Rust Tuple Details

A tuple is one value that packs a few values into a fixed order. A hard limit caps how long a printable tuple can be.

A one-value tuple needs the comma

The trailing comma is the whole difference between a tuple and a plain value in brackets:

let single = (5u32,);
let plain = (5u32);
println!("single = {:?} plain = {}", single, plain);

The type names every part

A tuple type is the list of its part types, in order:

let reading: (u8, bool) = (1u8, true);
println!("{:?}", reading);

Tuples inside tuples

A part can be a whole tuple of its own:

let nested = ((1, 2), (4, -1));
println!("nested = {:?}", nested);

Chained dots read deep inside

nested.0.1 means: part 0 first, then its part 1:

let nested = ((1, 2), (4, -1));
println!("inner second = {}", nested.0.1);

Printing stops at twelve parts

Tuples print with {:?} up to 12 parts. A 13-part tuple has no Debug form:

let dozen = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
println!("{:?}", dozen);
// let one_more = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);
// println!("{:?}", one_more); // error E0277: a 13-part tuple has no Debug form

Example

fn main() {
    let single = (5u32,);
    let plain = (5u32);
    let nested = ((1u8, 2u16), (4u64, -1i8));
    println!("single = {:?} plain = {}", single, plain);
    println!("nested = {:?}", nested);
    println!("inner second = {}", nested.0.1);
    let bundle = (1, "hello", 4.5, true);
    let (a, b, c, d) = bundle;
    println!("{:?}, {:?}, {:?}, {:?}", a, b, c, d);
}

Key points

  • A tuple is one value made of a few values in a fixed order.

In this example, single is (5u32,) — the trailing comma makes it a one-value tuple, so {:?} prints it as (5,). plain is (5u32) with no comma. So it is simply the number 5. The compiler may even suggest removing the brackets. nested holds two tuples, and {:?} shows the whole shape: ((1, 2), (4, -1)). nested.0.1 walks in twice: part 0 is (1, 2), and its part 1 is 2. Last, bundle is split into a, b, c and d. One let pattern does the split. The four values print in order.

Note

The 12-part limit covers ready-made traits like Debug and Clone.

The limit does not cover tuples themselves.

A longer tuple still works as a value.

Its parts can be printed one by one.

A struct with named fields is the step up from a long tuple.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

Which of these is a tuple holding exactly one value?