Sub topic 6
What tuples can do: Debug, PartialEq, Ord, Default, and Copy
This chapter assumes you can create a tuple, read its fields, and know what a trait is. Tuples get several standard traits automatically, so you never write #[derive(...)] for them.
The rule: a tuple has a trait if all its elements do
The standard library implements these traits for tuples of up to 12 elements. Each implementation works only when every element type has the trait too.
| Trait | What it gives you | Requires from each element |
|---|---|---|
| `Debug` | `{:?}` and `{:#?}` printing | `Debug` |
| `PartialEq`, `Eq` | `==` and `!=` | `PartialEq`, `Eq` |
| `PartialOrd`, `Ord` | `<`, `>`, `.sort()`, `.max()` | `PartialOrd`, `Ord` |
| `Default` | `Default::default()` | `Default` |
| `Clone`, `Copy` | `.clone()`, implicit copies | `Clone`, `Copy` |
| `Hash` | use as a `HashMap` key or in a `HashSet` | `Hash` |
Display is not on the list. You cannot print a tuple with {}. Use {:?} or format the fields yourself.
Seeing each trait in action
use std::collections::HashSet;
fn main() {
let a = (1, "apple", 2.5);
let b = (1, "apple", 2.5);
println!("{:?}", a);
println!("{}", a == b);
println!("{}", (1, 9) < (2, 0));
println!("{}", (1, 9) < (1, 10));
let mut people = vec![(30, "Bo"), (25, "Cy"), (30, "Al")];
people.sort();
println!("{:?}", people);
let d: (i32, bool, String) = Default::default();
println!("{:?}", d);
let p = (3, 'x');
let q = p;
println!("{:?} {:?}", p, q);
let mut seen = HashSet::new();
seen.insert((1, 2));
println!("{}", seen.contains(&(1, 2)));
}The output is:
(1, "apple", 2.5)
true
true
true
[(25, "Cy"), (30, "Al"), (30, "Bo")]
(0, false, "")
(3, 'x') (3, 'x')
trueOrdering is lexicographic
Comparison looks at the first fields. If they are equal, it moves to the next pair, as a dictionary does with letters. That is why (1, 9) < (2, 0) is true, and why the sort above breaks the tie between two 30-year-olds by name. To sort by a different priority, put that field first or use sort_by_key.
Copy depends on the contents
(i32, char) is Copy, so let q = p; leaves p usable. (i32, String) is not Copy, because String owns heap memory. Assigning it moves the whole tuple.
Exercise
Does (1, String::from("a")) == (1, String::from("a")) compile, and is let t = (1, String::new()); let u = t; println!("{:?}", t); valid?
Show answer
The comparison compiles, because both i32 and String implement PartialEq. The second snippet is invalid. The tuple contains a String, so it is not Copy. let u = t; moves it, and t can no longer be used.
Exercise
What does (2, "b") < (2, "a") evaluate to, and why?
Show answer
It is false. The first fields are equal, so comparison moves to the second fields. "b" is greater than "a", so the left tuple is greater.