Sub topic 6
What tuples can do: Debug, PartialEq, Ord, Default, and Copy
This chapter assumes you can create tuples, read fields with .0, and destructure them. It also assumes you know what a trait is and what derive does. Here you will see which standard traits tuples already implement, when they implement them, and where that stops being enough.
The rule: a tuple has a trait if every element has it
You never write impl Debug for (i32, String). The standard library implements these traits for tuples generically, and the implementation requires each element type to implement the trait too.
The standard library provides these implementations for tuples up to 12 elements long. The unit type () implements them as well.
| Trait | What it gives you | Requires every element to be |
|---|---|---|
| `Debug` | `{:?}` and `{:#?}` formatting | `Debug` |
| `Clone` | `.clone()` | `Clone` |
| `Copy` | implicit bitwise copies | `Copy` |
| `PartialEq`, `Eq` | `==` and `!=` | `PartialEq`, `Eq` |
| `PartialOrd`, `Ord` | `<`, `>`, `cmp`, sorting | `PartialOrd`, `Ord` |
| `Hash` | use as a `HashMap` key | `Hash` |
| `Default` | `Default::default()` | `Default` |
Display is missing from the table. Tuples do not implement it, so println!("{}", (1, 2)) does not compile. Use {:?}.
Debug
fn main() {
let t = (1, "two", 3.0);
println!("{:?}", t);
println!("{:#?}", t);
}The first line prints (1, "two", 3.0). The {:#?} form prints each element on its own indented line, which helps when elements are large.
Equality and ordering
Two tuples are equal when they have the same type and all elements are equal. Ordering is lexicographic. Rust compares the first elements, and it moves to the second only when the first are equal, and so on.
fn main() {
let a = (1, "apple");
let b = (1, "banana");
println!("{}", a == b);
println!("{}", a < b);
println!("{:?}", a.cmp(&b));
println!("{:?}", (2, 0).cmp(&(1, 99)));
}This prints false, true, Less, and Greater. The first elements of a and b tie, so the strings decide. In the last line the first elements already differ, so 99 is never compared.
Lexicographic ordering makes tuples good sort keys. To sort by age descending and then by name ascending, build a tuple key:
use std::cmp::Reverse;
fn main() {
let mut people = vec![("Ada", 36), ("Grace", 45), ("Alan", 36)];
people.sort_by_key(|&(name, age)| (Reverse(age), name));
println!("{:?}", people);
}The output is [("Grace", 45), ("Ada", 36), ("Alan", 36)]. Reverse flips the comparison for one element without affecting the others.
Floats limit what a tuple can do
f64 implements PartialEq and PartialOrd but not Eq or Ord, because NaN is not equal to itself. A tuple inherits that limit.
fn main() {
let a = (1, f64::NAN);
let b = (1, f64::NAN);
println!("{}", a == b);
println!("{:?}", a.partial_cmp(&b));
}This prints false and None. The type (i32, f64) is therefore not Ord, and vec.sort() on a Vec<(i32, f64)> fails to compile. Sort it with a closure instead:
fn main() {
let mut readings = vec![(2, 0.5), (1, 9.0), (1, 3.5)];
readings.sort_by(|a, b| a.partial_cmp(b).unwrap());
println!("{:?}", readings);
}The unwrap panics if the data contains NaN. If that can happen, use f64::total_cmp on the float field or filter the values out first.
Default
Default::default() on a tuple builds each element's default value.
fn main() {
let d: (i32, bool, String, Option<u8>) = Default::default();
println!("{:?}", d);
let best: Option<(i32, i32)> = None;
println!("{:?}", best.unwrap_or_default());
}The first line prints (0, false, "", None). The second prints (0, 0). unwrap_or_default is a convenient way to get a neutral pair when a computation like min_max finds nothing.
Copy, Clone, and partial moves
A tuple is Copy only if all elements are Copy. This decides whether assignment copies the value or moves it.
fn main() {
let a = (1, 2.5);
let b = a;
println!("{:?} {:?}", a, b);
let s = (1, String::from("hi"));
let copy = s.clone();
let name = s.1;
println!("{} {} {:?}", s.0, name, copy);
}a is still usable after let b = a because (i32, f64) is Copy. (i32, String) is not Copy, so it needs an explicit .clone() to duplicate.
The line let name = s.1; moves only the String out of s. This partial move is allowed for tuples, and the remaining field s.0 is still readable. Using s as a whole afterwards would be a compile error.
Hash and tuple keys
Because tuples implement Hash and Eq when their elements do, they work as composite keys without defining a struct.
use std::collections::HashMap;
fn main() {
let mut grid: HashMap<(i32, i32), char> = HashMap::new();
grid.insert((0, 0), '#');
grid.insert((1, 0), '.');
println!("{:?}", grid.get(&(0, 0)));
}This prints Some('#').
Common errors
(T1, T2)doesn't implementDisplay. Switch to{:?}or format each field yourself.the trait bound f64: Ord is not satisfied. A float inside the tuple blockssort(),max(), andBTreeMapkeys. Usesort_bywithpartial_cmportotal_cmp.borrow of moved value. A non-Copyelement made the whole tuple non-Copy. Clone it, borrow it, or move only the fields you need.- Comparing tuples of different types.
(1, 2) == (1, 2, 3)does not compile, because the types differ. - Tuples longer than 12 elements. They lose these implementations. At that size, a struct with
#[derive(...)]is the better design anyway.
Exercise
You have let mut v: Vec<(u32, f64)> = vec![(2, 1.5), (1, 4.0)];. Why does v.sort() fail to compile, and what is one way to sort v?
Show answer
f64 does not implement Ord, so (u32, f64) does not implement Ord either, and sort() requires Ord. Sort with v.sort_by(|a, b| a.partial_cmp(b).unwrap());, or compare the float with f64::total_cmp to avoid a panic on NaN.
Exercise
Given let s = (5, String::from("x")); let t = s.1;, can you still print s.0? Can you pass s to a function that takes (i32, String)?
Show answer
You can print s.0, because only the field s.1 was moved, and i32 is Copy anyway. You cannot pass s as a whole, because part of it has been moved out.