Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 132 ยท Variables and Types

Tuples and the Unit Type

Learn Rust tuples - creating them, indexing with .0, destructuring, nesting, returning several values, comparing and printing tuples, and the unit type () that functions return by default.

Sometimes a function naturally produces more than one value: a minimum and a maximum, a quotient and a remainder, a name and an age. You could define a struct for every such pair, but that is a lot of ceremony for a throwaway grouping. Rust has a lightweight alternative built into the language: the tuple, a fixed-size group of values that may have different types.

This lesson shows how to create tuples, read their fields, take them apart with destructuring, return several values from a function, and compare and print them. It also introduces the unit type (), a tuple with zero fields that turns out to be everywhere in Rust, even in code that never mentions it. Arrays, which hold many values of the same type, come in the next lesson.

Creating a tuple

A tuple is written as a comma-separated list in parentheses. The type is written the same way, listing the type of each position:

Rust Your first tuples

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

point has the type (i32, i32), and person has the type (&str, i32, bool). Each position has its own type, and the whole tuple type is made of all of them. A tuple of (i32, i32) and a tuple of (i32, i64) are different, unrelated types. The compiler infers the types in person from the literals, so you rarely have to write them out.

Tuples do not implement Display, because there is no single obvious way to print one. They do implement Debug, so you print them with {:?}, as above. The {point:?} form is a captured identifier, which printing explained.

A tuple is stored inline, exactly like the fields of a struct: no heap allocation, no pointer, nothing extra. A (i32, i32) takes eight bytes, and a function can pass it around in registers.

Reading fields with .0, .1, .2

You access a tuple field with a dot and the position, counted from zero. The position is a literal number, not a variable:

Rust Accessing tuple fields by position

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Because the position is part of the syntax, the compiler knows at compile time that the field exists and what type it has. There is no "index out of range" at runtime. If you write car.3, the program does not compile:

Rust A field that does not exist (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The compiler reports error[E0609]: no field `2` on type `({integer}, {integer})` . The error comes from the type checker, long before the program could run.

You also cannot use a variable as an index (pair.i looks for a field named i). If you need to pick a position at runtime, you want an array or a Vec, not a tuple.

Tuples are mutable only as a whole. A let car = (...) binding without mut forbids car.2 = 89.0, just like any other variable. You cannot make just one field mutable.

Destructuring

Reading fields as .0 and .1 gets unreadable quickly. A better way is to destructure the tuple: a let with a tuple pattern on the left gives every field its own name in one step.

Rust Taking a tuple apart

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Patterns are a big topic that gets its own lesson (patterns in depth), but a few rules are already visible:

  • The pattern must have exactly the same number of positions as the tuple, unless you use .. to stand for "all the others".
  • _ matches any value and does not bind it, so there is no unused-variable warning.
  • Each name in the pattern becomes a new variable. Here drink is a &str, cups is an i32 and price_each is an f64.

Destructuring works almost everywhere a variable is introduced: in let, in function parameters, in for loops and in match arms. A very common use is looping over a list of pairs:

Rust Destructuring in a for loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

In the second loop, &scores yields references to tuples, so the pattern &(name, score) strips the reference and copies the fields out. Tuples of Copy types are themselves Copy, which is why let mut best = scores[0] works without any move or clone (see ownership and Copy and Clone).

Swapping without a temporary

Destructuring assignment lets you assign to existing variables, not just create new ones. That gives a pleasant way to swap values:

Rust Swapping and destructuring assignment

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The right-hand side is evaluated completely first, then the values are assigned. That is why (a, b) = (b, a) is correct.

Returning several values

The most common use of tuples is returning more than one value from a function. Rust has no "out parameters", so a tuple is the natural answer:

Rust A function that returns a tuple

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

divide returns a (i32, i32), and the caller destructures it at once. min_max shows tuples combined with Option: Option<(i32, i32)> is "either nothing, or a pair". The ? operator on values.first() returns None early when the slice is empty (the ? operator gets a full lesson).

The standard library uses tuples the same way: str::split_at returns a pair of slices, i32::overflowing_add returns (result, did_overflow), Iterator::enumerate yields (index, item), and HashMap iterates over (&key, &value) pairs.

When a tuple has more than two or three fields, or when the positions are easy to confuse ((f64, f64, f64) is a position, a color, or a velocity?), define a struct with named fields instead. .0 and .1 are fine for short-lived pairs, but names document themselves.

Nested tuples and one-element tuples

Tuples can hold other tuples, and patterns nest in the same way:

Rust Nested tuples and the one-element tuple

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

segment.1.0 reads the first field of the second field. Chained positions work in current Rust; older code sometimes wrote (segment.1).0.

Notice the trailing comma in (5,). Without it, (5) is just the number 5 in parentheses, the same as in arithmetic. The comma is what makes a one-element tuple. One-element tuples are rare, but you will meet them when a generic API expects a tuple and you have exactly one thing to give it.

(The let not_a_tuple = (5); line makes rustc warn about unnecessary parentheses. It is there on purpose, to show the difference. In real code you would simply write 5.)

Comparing and printing

Tuples compare lexicographically: first the first fields; only if those are equal, the second fields; and so on. This works whenever every field type supports the comparison, so tuples of numbers, strings and booleans work out of the box. The same is true for Debug, Clone, Copy, Default, Hash and Eq.

Rust Comparison, sorting and pretty-printing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Sorting a Vec of tuples sorts by the first field, then by the second to break ties. This gives you a free multi-key sort: put the most important key first. To sort by something else, see sorting and searching.

Comparing with < requires the types to match exactly, so (1, 2) < (1, 2, 3) does not compile: the two types have different sizes.

Tuples implement the standard traits only up to a certain size (12 fields at the time of writing). That is a library limit, not a language one, and a tuple that large is a strong sign that you want a struct.

The unit type ()

A tuple with no fields is written () and called the unit type. It has exactly one value, which is also written (). It carries no information, and it takes up zero bytes.

You already use it all the time. A function with no -> return type returns ():

Rust Functions without a return type return unit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Both functions return (), so a and b are both (), and they are equal (there is only one possible value). -> () and no return type mean the same thing; the shorter form is the convention. A block whose last statement ends with a semicolon also produces (), which is why leaving off a semicolon on the last line of a function changes what it returns. Rust syntax explained that rule.

Unit appears in many places once you know to look:

  • Result<(), E> means "success carries no data, but failure carries an error". It is the standard return type for operations such as writing a file (see Result).
  • HashMap<K, ()> is a set. The standard HashSet<K> is built that way.
  • Option<()> is a boolean with extra steps; occasionally useful with ?.
  • An if without else must have a unit-typed block, because when the condition is false the whole expression evaluates to ().

That last point leads to a classic beginner error: using a value-producing if without an else. If expressions covers it in detail. The mismatch is also visible with plain functions:

Rust A stray semicolon changes the type (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The compiler reports error[E0308]: mismatched types, pointing at the return type and explaining that "implicitly returns () as its body has no tail or return expression". It even suggests removing the semicolon. That is the fix: write x * 2 without a semicolon, so the block's value is the return value.

Tuples versus other options

Need Use
A quick pair or triple, used in one place tuple
Fields that need names, methods, or are used across the code base struct (a tuple struct if one field wraps another type)
Many values of the same type, fixed count array
Many values of the same type, growing Vec
One value that is one of several kinds enum

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which expression reads the second field of a tuple named t?

    Tuple fields are read with a dot and a literal position starting at zero, so the second field is t.1. Square brackets are for arrays and slices.
  2. 2. What is the type of (5,)?

    The trailing comma makes it a tuple with one field. Without the comma, (5) is just the number 5 in parentheses.
  3. 3. What does let (a, _, c) = (1, 2, 3); do?

    The underscore pattern matches anything without binding it. The pattern has three positions, like the tuple, so it is accepted.
  4. 4. A function is declared as fn total(v: &[i32]) -> i32 { v.iter().sum(); }. Why does it fail to compile?

    With the trailing semicolon the block has no tail expression, so it evaluates to the unit type (), which does not match i32. Remove the semicolon.
  5. 5. How do tuples compare with <?

    Comparison is lexicographic: the first fields are compared, and only if they are equal does the next pair of fields matter.

Summary

  • A tuple groups a fixed number of values of possibly different types: (i32, &str, bool). It lives inline, with no heap allocation.
  • Read fields with .0, .1, ...; the position is a literal and is checked at compile time.
  • Destructure with let (a, b) = t;; use _ to ignore a field and .. to skip several. Destructuring assignment such as (a, b) = (b, a) swaps variables.
  • Tuples are the idiomatic way to return several values; switch to a struct when fields need names.
  • Tuples compare and sort lexicographically and support Debug, Clone, Copy, Hash and Default when all fields do.
  • () is the unit type with exactly one value. Functions without a return type, semicolon-ended blocks and Result<(), E> all use it.

Next: Arrays