Ciência da computação · Livro 4 · Graduação — Ano 2

University Computer Science — Year 2

Este livro ainda não está disponível em Português. Edições: English.

University Computer Science — Year 2 · Graduação — Ano 2

8Traits and Generics

println!("{}", x) prints integers, floats, strings, and, after five lines of code, a type of our own that the authors of println! never saw.

struct Book {
    title: String,
    pages: u32,
}

impl fmt::Display for Book {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} ({} pages)", self.title, self.pages)
    }
}

fn main() {
    let b = Book { title: "The Paper Forest".to_string(), pages: 133 };
    println!("{b}");                          // println! calls Display::fmt
    let line = format!("[{b:>30}]");       // so does format!, with its width ignored by write!
    let owned: String = b.to_string();        // and to_string, given to every Display type
    println!("{line}\n{} characters", owned.len());
}
Listing 8.1. A book that prints itself code/bachelor-2/08-rust-traits-and-generics/listings/display.rs
$ rustc --edition 2021 -O -o display display.rs && ./display
The Paper Forest (133 pages)
[The Paper Forest (133 pages)]
28 characters
Output 8.1. One method written, three ways to print. The width 30 had no effect.

println!, format! and to_string ask one thing of their argument: that its type implements the trait Display, a one-method interface. This chapter is about such interfaces, the functions written once for every type that has them, and the two ways, by copies or by tables, in which the compiler turns them into machine code.

You already know

Chapter 3: a virtual function is called through the object’s pointer to its class’s table, at a cost of one indirect call. Chapter 4: a template is instantiated once per argument type, and a concept states what the argument must provide. Chapter 7: a derive attribute writes Debug, PartialEq and orders for a type.

8.1 Traits

Definition 8.1 (Trait, trait implementation, default method)

A trait is a named set of method signatures, and possibly of associated types and constants, that a type may provide. A trait implementation, impl Trait for Type { ... }, gives the bodies for one type. A default method is a method whose body is written in the trait itself, in terms of the other methods; an implementation may keep it or replace it.

trait Lendable {
    fn title(&self) -> String;
    fn loan_days(&self) -> u32; // required: each type says its own

    fn describe(&self) -> String {
        // a default method: written once, in terms of the required ones
        format!("{}, lent for {} days", self.title(), self.loan_days())
    }
}

struct Book { title: String }
struct Film { title: String, minutes: u32 }

impl Lendable for Book {
    fn title(&self) -> String { self.title.clone() }
    fn loan_days(&self) -> u32 { 21 }
}

impl Lendable for Film {
    fn title(&self) -> String { format!("{} (film)", self.title) }
    fn loan_days(&self) -> u32 { 7 }
    fn describe(&self) -> String {
        // overrides the default
        format!("{}, {} min, back within {} days", self.title(), self.minutes, self.loan_days())
    }
}
Listing 8.2. A trait for what the library lends code/bachelor-2/08-rust-traits-and-generics/listings/bounds.rs

Book keeps the default describe; Film replaces it. Unlike a C++ base class, a trait has no fields and is not a type of values; and an implementation may be written after both the type and the trait, in another file, as Display was for Book. One restriction keeps this sound.

Definition 8.2 (Coherence, orphan rule)

Coherence requires that a program have at most one implementation of a given trait for a given type. Rust enforces it by the orphan rule: a crate may write impl Trait for Type only if the trait or the type is defined in that crate.

So our crate may implement Display for Book (our type) or Lendable for String (our trait), but not Display for Vec<u32>: two crates could each write one, and the program would not know which to call. The usual way round is a newtype (Section 8.5).

8.2 Generic functions and trait bounds

Definition 8.3 (Generic function, trait bound)

A generic function has type parameters, fn f<T>(...), and is checked once, for every type its parameters may take. A trait bound T: Trait restricts T to types that implement Trait, and is the only source of what the body may do with a T. Bounds are written in the angle brackets, in a where clause, or as impl Trait in a parameter’s type.

fn longest_loan<T: Lendable>(items: &[T]) -> u32 {
    items.iter().map(|i| i.loan_days()).max().unwrap_or(0)
}

fn label<T>(item: &T, shelf: impl Display) -> String
where
    T: Lendable,
{
    format!("[{shelf}] {}", item.describe())
}

fn main() {
    let books = [Book { title: "The Silent Code".into() },
        Book { title: "Seven Comets".into() }];
    let film = Film { title: "Harbour Lights".into(), minutes: 94 };
    println!("{}", label(&books[0], 'B'));
    println!("{}", label(&film, 12));
    println!("{}", longest_loan(&books));
}
Listing 8.3. Three ways to write a bound code/bachelor-2/08-rust-traits-and-generics/listings/bounds.rs
$ rustc --edition 2021 -O -o bounds bounds.rs && ./bounds
[B] The Silent Code, lent for 21 days
[12] Harbour Lights (film), 94 min, back within 7 days
21
Output 8.2. label accepts a char and an integer as the shelf: both are Display.

A body that uses an operation its bounds do not promise is refused, before any call is seen:

fn largest<T: Copy>(xs: &[T]) -> T {
    let mut best = xs[0];
    for &x in xs {
        if x > best {
            best = x;
        }
    }
    best
Listing 8.4. A comparison with no bound code/bachelor-2/08-rust-traits-and-generics/listings/missing_bound.rs
error[E0369]: binary operation `>` cannot be applied to type `T`
 --> missing_bound.rs:6:14
  |
6 |         if x > best {
  |            - ^ ---- T
  |            |
  |            T
  |
help: consider further restricting type parameter `T` with trait `PartialOrd`
  |
3 | fn largest<T: Copy + std::cmp::PartialOrd>(xs: &[T]) -> T {
  |                    ++++++++++++++++++++++
Output 8.3. The compiler names the missing trait. Some lines are left out.

This is the difference with C++ templates. A template’s body is checked only when it is instantiated, against the actual type, and an error inside it surfaces at the caller, often deep in a library (Chapter 4); a concept may state requirements, but the body is not checked against them. A Rust generic body is checked once, against its bounds: if it compiles, it compiles for every type that satisfies them, and a caller’s error is only ever this type does not implement that trait.

Definition 8.4 (Monomorphisation)

Monomorphisation is the compilation of a generic function into one machine-code copy for each combination of type arguments with which the program uses it, each copy compiled and optimised as if it had been written for those types.

pub fn largest<T: PartialOrd + Copy>(xs: &[T]) -> T {
    let mut best = xs[0];
    for &x in xs {
        if x > best {
            best = x;
        }
    }
    best
}

pub fn largest_pages(pages: &[u32]) -> u32 {
    largest(pages) // instantiates largest::<u32>
}

pub fn warmest(temps: &[f64]) -> f64 {
    largest(temps) // instantiates largest::<f64>
}
Listing 8.5. One generic, two uses code/bachelor-2/08-rust-traits-and-generics/listings/mono.rs
$ rustc --edition 2021 --crate-type lib -C opt-level=1 -C symbol-mangling-version=v0 --emit obj mono.rs
$ nm -C mono.o | grep -o 'mono::.*' | sort
mono::largest::<f64>
mono::largest::<u32>
mono::largest_pages
mono::warmest
Output 8.4. The symbols of the object file: largest exists twice.

Proposition 8.5 (One copy per type)

Let a program call a generic function f<T>, directly or through other generic functions, with the set T\mathcal{T} of type arguments, once all generic calls are expanded. Then the compiled program contains at most ∣T∣|\mathcal{T}| copies of f, one per element of T\mathcal{T}, whatever the number of call sites.

Proof. The compiler generates a copy of f for a type argument when it first meets a call with it, and records it; every later call with the same argument, from any site, uses the recorded copy. A copy is made only for an argument that some call uses, so the copies are in bijection with a subset of T\mathcal{T}: at most ∣T∣|\mathcal{T}|. (Fewer when the optimiser inlines a copy everywhere and drops it, or merges two identical copies, as the weekend problem will show.) ∎

The copies are fast, since each is specialised: largest::<u32> compares with an integer instruction, the f64 one with a floating-point one, with no indirection. They also cost space and compile time, in proportion to ∣T∣|\mathcal{T}|.

8.3 Trait objects

A vector holds values of one type. To hold rectangles and circles together, the program needs one type for any value that implements Shape.

Definition 8.6 (Trait object, fat pointer)

A trait object dyn Trait is a value of some type implementing Trait, whose type is known only at run time. It is used behind a pointer, &dyn Trait or Box<dyn Trait>, which is a fat pointer: the address of the value together with the address of a table, the vtable, holding the value type’s size, alignment, drop function and the addresses of its implementations of the trait’s methods.

fn total_area(shapes: &[Box<dyn Shape>]) -> f64 {
    shapes.iter().map(|s| s.area()).sum() // each call goes through the object's table
}

fn main() {
    let plots: Vec<Box<dyn Shape>> = vec![
        Box::new(Rect { w: 4.0, h: 5.0 }),
        Box::new(Circle { r: 1.5 }),
        Box::new(Rect { w: 2.0, h: 2.5 }),
    ];
    for s in &plots {
        println!("{:<7}{:>6.2}", s.name(), s.area());
    }
    println!("total  {:>6.2}", total_area(&plots));
}
Listing 8.6. Two types in one vector code/bachelor-2/08-rust-traits-and-generics/listings/shapes_dyn.rs
$ rustc --edition 2021 -O -o shapes_dyn shapes_dyn.rs && ./shapes_dyn
rect    20.00
circle   7.07
rect     5.00
total   32.07
Output 8.5. Each area call reaches the right implementation.

fat_pointer.rs prints the sizes of a few pointers and reads the two halves of three trait-object references.

fn parts(s: &dyn Shape) -> (usize, usize) {
    // a &dyn Shape is (value's address, table's address): today's order, not a promise
    let [data, table]: [usize; 2] = unsafe { std::mem::transmute(s) };
    (data, table)
}
Listing 8.7. The two words of a &dyn Shape code/bachelor-2/08-rust-traits-and-generics/listings/fat_pointer.rs
$ rustc --edition 2021 -O -o fat_pointer fat_pointer.rs && ./fat_pointer
&Circle 8  &dyn Shape 16  Box<dyn Shape> 16  &[u32] 16  &str 16
areas [3.0, 12.0, 2.0]
data pointers differ: true
two circles share a table: true; the rect has its own: true
Output 8.6. Sizes in bytes, on a target with 8-byte pointers.

Proposition 8.7 (A trait object reference is two pointers)

A reference or box to a dyn Trait occupies two machine words, the data pointer and the vtable pointer. One table per type and trait suffices for all the values of that type.

Proof. A call s.area() on s: &dyn Shape must find, at run time, the code of area for the value’s type, and, to drop a Box<dyn Shape>, its drop function and size. These depend on the type, not on the value, so one table per (type, trait) pair suffices, a constant in the program; the value’s address is a second word, since the value itself may be anywhere. The value is not changed, so the table address cannot be inside it: it travels in the pointer. Two words, as printed for &dyn Shape and Box<dyn Shape>; the slices &[u32] and &str are fat pointers too, with a length as second word. ∎

The compiler normally emits one table per type and trait in each compilation unit, which is what the last line of Output 8.6 sees in this one-file program. Rust promises neither that the address is unique (a table may be duplicated across units) nor that two types get different ones (identical tables may be merged), and the order of the two words is not a documented layout either: never compare table pointers to test a type.

Where the table pointer lives. In Rust it travels in the reference, so a Circle stays 8 bytes and gains no hidden field; only the references used as trait objects grow, to 16 bytes. In C++ every object of a class with virtual functions carries it, whether or not it is ever called virtually.
Where the table pointer lives. In Rust it travels in the reference, so a Circle stays 8 bytes and gains no hidden field; only the references used as trait objects grow, to 16 bytes. In C++ every object of a class with virtual functions carries it, whether or not it is ever called virtually.

Not every trait can be used this way.

Definition 8.8 (Object safety)

A trait is object safe, or dyn compatible, if dyn Trait can be formed: its methods can be called through a vtable. Methods that return Self by value, or have type parameters of their own, break this (the caller does not know the size of Self; a generic method would need one table entry per type argument), unless they are excluded with where Self: Sized.

trait Duplicate {
    fn duplicate(&self) -> Self; // the caller must know the size of Self
}

struct Card { number: u32 }

impl Duplicate for Card {
    fn duplicate(&self) -> Self { Card { number: self.number } }
}

fn main() {
    let cards: Vec<Box<dyn Duplicate>> = vec![Box::new(Card { number: 7 })];
    println!("{}", cards.len());
}
Listing 8.8. A method that returns Self code/bachelor-2/08-rust-traits-and-generics/listings/object_safety.rs
error[E0038]: the trait `Duplicate` is not dyn compatible
  --> object_safety.rs:14:28
   |
   |       --------- this trait is not dyn compatible...
 4 |     fn duplicate(&self) -> Self; // the caller must know the size of Self
Output 8.7. The message uses the newer name, dyn compatible. Some lines are left out.
Static and dynamic dispatch. Above, a generic is copied per type and each copy calls its methods directly, where they can be inlined. Below, a function on trait objects exists once, and each call goes through the vtable of the value at hand.
Static and dynamic dispatch. Above, a generic is copied per type and each copy calls its methods directly, where they can be inlined. Below, a function on trait objects exists once, and each call goes through the vtable of the value at hand.

The two costs can be measured. dispatch_cost.rs sums the areas of a million shapes, twenty times, through a generic function over rectangles only, through a match on an enum of the two shapes (Chapter 7), and through boxed trait objects.

enum Any { R(Rect), S(Square) }

fn sum_generic<T: Shape>(xs: &[T]) -> f64 { xs.iter().map(|x| x.area()).sum() } // per T
fn sum_enum(xs: &[Any]) -> f64 {
    xs.iter().map(|x| match x { Any::R(r) => r.area(), Any::S(s) => s.area() }).sum()
}
fn sum_dyn(xs: &[Box<dyn Shape>]) -> f64 { xs.iter().map(|x| x.area()).sum() } // via the table
Listing 8.9. The three sums code/bachelor-2/08-rust-traits-and-generics/listings/dispatch_cost.rs
$ rustc --edition 2021 -C opt-level=3 dispatch_cost.rs -o dispatch_cost
$ ./dispatch_cost
generic, rects only     0.72 ns per shape   (check 119999880)
enum, mixed             1.43 ns per shape   (check 70000000)
dyn, mixed              2.80 ns per shape   (check 70000000)
$ ./dispatch_cost
generic, rects only     0.92 ns per shape   (check 119999880)
enum, mixed             1.46 ns per shape   (check 70000000)
dyn, mixed              2.93 ns per shape   (check 70000000)
Output 8.8. Measured on the author’s laptop, two runs; the times vary from run to run.

The generic loop is the fastest: no call at all remains, and the loop is unrolled; what is left is one chain of additions. The enum costs a test per shape; trait objects cost an indirect call, and a pointer to follow to each box, about twice the enum. A few nanoseconds per call matters only in inner loops: trait objects are the right tool for a list of plugins, handlers or shapes of open-ended kinds, an enum for a closed set of kinds, a generic for code that must be fast for each type.

8.4 The standard traits

A handful of traits of the standard library give a type its everyday abilities; most can be derived.

traitgivesderive?
Debug, Display{:?} and {} printingDebug only
Clone, Copy.clone(); copy on assignment instead of moveyes
PartialEq, Eq==; Eq promises reflexivity, x=xx = xyes
PartialOrd, Ord<, partial_cmp; Ord: a total order, cmp, sortyes
Hasha key of HashMap and HashSetyes
DefaultT::default()yes
From, Intoconversions, used by ?no
Add, Mul, Neg, …the operators +, *, unary -no
Iteratorfor loops, map, sum (Chapter 9)no
Dropcode run when the value is droppedno
The comparison traits. An arrow goes from a trait to one that requires it: a type can implement Ord only if it implements Eq and PartialOrd.
The comparison traits. An arrow goes from a trait to one that requires it: a type can implement Ord only if it implements Eq and PartialOrd.

Derived comparisons follow the order in which the fields are written.

Proposition 8.9 (Derived orders are lexicographic)

For a struct with fields f1,…,fnf_1, \dots, f_n in this order, the derived Ord compares aa and bb by their first fields, and if equal by their second, and so on: the lexicographic order on (a.f1,…,a.fn)(a.f_1, \dots, a.f_n). For an enum, a value of an earlier variant is smaller than one of a later variant, and two values of the same variant compare lexicographically on their fields. If the order of every field type is total, the derived order is total.

Proof. The first two claims describe the derived code, which is a.f1.cmp(&b.f1) followed, while the result is Equal, by the next fields; for an enum, the comparison of the variants’ indices comes first. Totality, for a struct, by induction on nn. For n=0n = 0 all values are equal. For n≥1n \ge 1: if a.f1≠b.f1a.f_1 \ne b.f_1, the total order on f1f_1 puts one first, and so does the derived order; if a.f1=b.f1a.f_1 = b.f_1, the derived order is that of the remaining n−1n - 1 fields, total by the induction hypothesis. Transitivity and antisymmetry follow in the same way (Exercise 8.8). For an enum, the variant indices are integers, totally ordered, and within one variant the struct case applies. ∎

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
struct Person {
    last_name: String, // compared first
    first_name: String,
    birth_year: u32,
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
enum AgeGroup {
    Child, // the smallest: variants compare in the order they are written
    Adult,
    Senior,
}

fn group(p: &Person) -> AgeGroup {
    match 2025 - p.birth_year {
        0..=17 => AgeGroup::Child,
        18..=64 => AgeGroup::Adult,
        _ => AgeGroup::Senior,
    }
}
Listing 8.10. Derived orders on a person and an age group code/bachelor-2/08-rust-traits-and-generics/listings/people_sort.rs
$ ./people_sort
Ashby Hana 2001
Ashham Dev 1968
Ashmore Gil 1992
oldest: Milo Brookworth
{Child: 14, Adult: 81, Senior: 25}
Output 8.9. The town’s 120 people, by name, by age, and counted by group. Some lines are left out.

f64 has no Ord: NaN compares neither smaller, equal nor greater than anything, itself included, so a vector of f64 cannot call sort.

$ rustc --edition 2021 -O -o float_sort float_sort.rs && ./float_sort
None None false
[-2.0, -0.1, 3.9, 4.3, 12.5, NaN]
[-0.1, 4.3, NaN, -2.0, 3.9, 12.5]
panicked at float_sort.rs:20:39:
called `Option::unwrap()` on a `None` value
[exit status 101]
Output 8.10. float_sort.rs: the comparisons of NaN, then three ways to sort [4.3, -0.1, NaN, 12.5, 3.9, -2.0].

f64::total_cmp is a total order on all bit patterns: a NaN with its sign bit clear, such as f64::NAN, comes after +∞+\infty, and one with the sign bit set before −∞-\infty. Treating NaN as equal to everything gives a relation that is not transitive (−0.1=NaN=12.5-0.1 = \mathrm{NaN} = 12.5, yet −0.1<12.5-0.1 < 12.5), and the sort, whose correctness assumes an order, returns a vector that is not sorted. The unwrap at least stops.

Operators are traits too. a + b is Add::add(a, b), so implementing Add for a type gives it +.

Definition 8.10 (Associated type)

An associated type is a type named inside a trait, type Output;, that each implementation fixes. Add declares type Output, the type of a + b; Iterator declares type Item, the type of the elements it yields.

impl Add for V2 {
    type Output = V2; // an associated type: the type of a + b
    fn add(self, o: V2) -> V2 { V2 { x: self.x + o.x, y: self.y + o.y } }
}

impl Sub for V2 {
    type Output = V2;
    fn sub(self, o: V2) -> V2 { V2 { x: self.x - o.x, y: self.y - o.y } }
}

impl Mul<f64> for V2 {
    type Output = V2; // V2 * f64; f64 * V2 would need impl Mul<V2> for f64
    fn mul(self, k: f64) -> V2 { V2 { x: self.x * k, y: self.y * k } }
}
Listing 8.11. Plane vectors with +, - and * code/bachelor-2/08-rust-traits-and-generics/listings/vector2.rs
$ rustc --edition 2021 -O -o vector2 vector2.rs && ./vector2
V2 { x: 3.0, y: 4.0 } V2 { x: 3.5, y: 3.0 } V2 { x: -3.0, y: -4.0 }
V2 { x: 0.0, y: 0.0 } true
Output 8.11. Walking halfway from the library to the station.

An associated type differs from a type parameter in who chooses it: Mul<f64> for V2 and a possible Mul<V2> for V2 are two implementations, selected by the right operand’s type, but each fixes its own Output, so the type of a * b is never ambiguous.

8.5 Newtypes and zero cost

Definition 8.11 (Newtype)

A newtype is a struct with a single field, struct Metres(f64);, that gives an existing type a new name and a new set of operations: those implemented for it, and no others.

A newtype is used to give distinct meanings distinct types, a length and a time both stored as f64, and to implement a foreign trait for a foreign type, which the orphan rule forbids directly (Exercise 8.10 does it for bool).

Definition 8.12 (Zero-cost abstraction)

An abstraction of a language is zero-cost if a program written with it compiles to code no slower and no larger than the program a careful programmer would write without it, by hand.

Generics are zero-cost in this sense (a copy per type, as if written by hand); trait objects are not quite, by design: they buy the ability to mix types for an indirect call. Newtypes are the clearest case, and the weekend problem measures it.

In practice — Choosing between generics, enums and trait objects

Take a generic parameter when the type is known at compile time at every call site; an enum when the set of kinds is closed and you own it, so that a new kind is a compile error at every match; a trait object when the set is open, other crates add kinds, or the values must be mixed in one collection. Derive Debug on every type, and Clone, PartialEq, Eq, Hash, Ord where they make sense.

8.6 Exercises

Exercise 8.1 ★

Predict the five lines. Which name does each call reach, and why do the second and fourth lines differ from what one might expect?

impl Greet for Ada {
    fn name(&self) -> String { "Ada".into() }
}
impl Greet for Bob {
    fn name(&self) -> String { "Bob".into() }
    fn hello(&self) -> String { format!("hi, {}", self.name()) }
}
impl Bob {
    fn name(&self) -> String { "Robert".into() } // an inherent method with the same name
}

fn twice<T: Greet>(x: &T) -> String { format!("{} / {}", x.hello(), x.name()) }

fn main() {
    let (a, b) = (Ada, Bob);
    println!("{}", a.hello());
    println!("{}", b.hello());
    println!("{}", b.name());
    println!("{}", twice(&b));
    let all: [&dyn Greet; 2] = [&a, &b];
    println!("{}", all.iter().map(|g| g.name()).collect::<Vec<_>>().join(", "));
}
Listing 8.12. Trait methods, inherent methods, generics and dyn code/bachelor-2/08-rust-traits-and-generics/listings/exo_which.rs
Solution

Solution of Exercise 8.1.

$ rustc --edition 2021 -O -o exo_which exo_which.rs && ./exo_which
hello, Ada
hi, Robert
Robert
hi, Robert / Bob
Ada, Bob
Output 8.15. The five lines.

a.hello(): Ada keeps the default, which calls the trait’s name. b.hello(): Bob’s own hello, whose self.name() has self: &Bob; method lookup prefers an inherent method to a trait method of the same name, so it reaches Robert. b.name(): the inherent one again. In twice, the body knows only T: Greet: x.name() can only mean the trait method, Bob, while x.hello() is still Bob’s hello, which says Robert. Through dyn Greet, only trait methods exist: Bob.

Exercise 8.2 ★

report does not compile, with three errors, two of them from one line. Find the bounds it needs, and write its signature with a where clause.

fn report<T>(items: &[T]) {
    for x in items {
        println!("{x}");
    }
    let distinct: HashSet<&T> = items.iter().collect();
    println!("{} distinct", distinct.len());
}

fn main() {
    report(&["Mill Lane", "Quay Street", "Mill Lane"]);
}
Listing 8.13. Printing and counting code/bachelor-2/08-rust-traits-and-generics/listings/exo_bound.rs
Solution

Solution of Exercise 8.2.

error[E0277]: `T` doesn't implement `std::fmt::Display`
 --> exo_bound.rs:7:19
  |
7 |         println!("{x}");
  |                   ^^^ `T` cannot be formatted with the default formatter
error[E0277]: the trait bound `T: Eq` is not satisfied
    --> exo_bound.rs:9:46
     |
   9 |     let distinct: HashSet<&T> = items.iter().collect();
Output 8.16. The first lines of the first two errors; the third asks for Hash on the same line. Some lines are left out.

println!("{x}") needs Display; a HashSet<&T> needs &T: Eq + Hash, that is T: Eq + Hash. The signature: fn report<T>(items: &[T]) where T: Display + Eq + Hash. With it the program prints the three names and 2 distinct.

Exercise 8.3 ★

Write a type Fraction that is always in lowest terms with a positive denominator, a constructor returning None for a zero denominator, and Display printing 3/4, -3/4, or 2 for a whole number. Make format!("{:>5}", f) pad the fraction. Why does the derived PartialEq then compare values correctly?

Solution

Solution of Exercise 8.3.

    pub fn new(num: i64, den: i64) -> Option<Fraction> {
        if den == 0 {
            return None;
        }
        let g = gcd(num, den);
        let s = if den < 0 { -1 } else { 1 }; // the sign goes to the numerator
        Some(Fraction { num: s * num / g, den: s * den / g })
    }
}

impl fmt::Display for Fraction {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let text = match self.den {
            1 => format!("{}", self.num),
            d => format!("{}/{}", self.num, d),
        };
        f.pad(&text) // pad, unlike write!, honours a width such as {:>8}
    }
}
Lowest terms and Display code/bachelor-2/08-rust-traits-and-generics/exercises/fraction.rs

write! ignores the width; f.pad applies it. A fraction in lowest terms with a positive denominator is the only representation of its value, so two fractions are equal as numbers exactly when their fields are equal: the derived PartialEq is right. Without the normalisation, 1/2 and 2/4 would compare unequal.

Exercise 8.4 ★

A program has fn show<T: Display>(x: T) and fn pair<A: Display, B: Display>(a: A, b: B), whose body calls show(a) and show(b). main calls show(3), show("Mill"), show(4), pair(1, "x") and pair("y", 2.5). How many copies of show and of pair does the compiled program contain (before inlining)? Justify with Proposition 8.5.

Solution

Solution of Exercise 8.4.

Expanding the calls, show is used with i32 (show(3), show(4), inside pair(1, "x")), &str (show("Mill"), inside both pairs) and f64 (inside pair("y", 2.5)): three copies. pair is used with (i32, &str) and (&str, f64): two copies. Five generated functions for two written; each extra call site with a known type adds none.

Exercise 8.5 ★★

Predict the two sorted lists, using Proposition 8.9. Then reorder the fields of Loan so that loans sort by title first: what else changes?

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
enum Shelf {
    Returns,
    Fiction(char), // the first letter of the author's name
    Reference,
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
struct Loan {
    due_day: u32,
    title: &'static str,
}

fn main() {
    let mut shelves =
        vec![Shelf::Reference, Shelf::Fiction('M'), Shelf::Returns, Shelf::Fiction('B')];
    shelves.sort();
    println!("{shelves:?}");
    let mut loans = vec![
        Loan { due_day: 12, title: "Seven Comets" },
        Loan { due_day: 3, title: "The Paper Forest" },
        Loan { due_day: 12, title: "Harbour Lights" },
    ];
    loans.sort();
    println!("{:?}", loans.iter().map(|l| l.title).collect::<Vec<_>>());
}
Listing 8.14. An enum and a struct, sorted code/bachelor-2/08-rust-traits-and-generics/listings/exo_derived.rs
Solution

Solution of Exercise 8.5.

$ rustc --edition 2021 -O -o exo_derived exo_derived.rs && ./exo_derived
[Returns, Fiction('B'), Fiction('M'), Reference]
["The Paper Forest", "Harbour Lights", "Seven Comets"]
Output 8.17. The two lists.

Variants compare in the order written: Returns first, Reference last, and the two Fiction values by their letters. Loans compare by due_day, then by title for the two due on day 12. With title first, the loans sort alphabetically, Harbour Lights, Seven Comets, The Paper Forest; == does not change (it compares all fields), but {:?} prints the fields in the new order.

Exercise 8.6 ★★

The median of seven temperatures comes out as −0.4-0.4. Explain, using the output, why the sort did not sort, and fix the program twice: with total_cmp, and by refusing NaN when the fields are parsed.

fn median(xs: &mut [f64]) -> f64 {
    xs.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal));
    xs[xs.len() / 2]
}

fn main() {
    let fields = ["4.3", "3.9", "NaN", "5.1", "-0.4", "2.8", "6.0"];
    let mut temps: Vec<f64> = fields.iter().map(|f| f.parse().unwrap()).collect(); // takes NaN
    println!("median {}", median(&mut temps));
    println!("{temps:?}");
}
Listing 8.15. A median code/bachelor-2/08-rust-traits-and-generics/listings/exo_nan.rs
median -0.4
[3.9, 4.3, NaN, -0.4, 2.8, 5.1, 6.0]
Output 8.12. The result and the vector. Some lines are left out.
Solution

Solution of Exercise 8.6.

"NaN".parse::<f64>() succeeds, and the comparator calls NaN equal to everything. The relation is not transitive, the sort’s work relies on it, and the vector comes out as printed: only the parts on each side of NaN sorted. The middle element, index 3, is −0.4-0.4. With total_cmp the vector is sorted, NaN last, and the median is 4.3, still computed over a meaningless value. The right fix is at the parse: reject a field whose value is not finite (v.is_finite()), as the weather parser of Chapter 7 rejects error codes; the median of the six readings is then 4.3 or 3.9, depending on which middle is taken.

Exercise 8.7 ★★

Write largest<T: PartialOrd + Copy>(xs: &[T]) -> Option<T>, then largest_ref, which needs no Copy. What does each return on [1.0, NaN, 3.0] and on [NaN, 3.0], and why?

Solution

Solution of Exercise 8.7.

pub fn largest<T: PartialOrd + Copy>(xs: &[T]) -> Option<T> {
    let mut it = xs.iter().copied();
    let mut best = it.next()?; // None for an empty slice
    for x in it {
        if x > best {
            best = x;
        }
    }
    Some(best)
}
The largest element, or None code/bachelor-2/08-rust-traits-and-generics/exercises/largest.rs

largest_ref returns &T and keeps best as a reference. On [1.0, NaN, 3.0]: 3.0, since NaN > 1.0 is false. On [NaN, 3.0]: NaN, since 3.0 > NaN is false too. The answer depends on where NaN stands: PartialOrd gives no maximum when an element is unordered.

Exercise 8.8 ★★

Complete the proof of Proposition 8.9: prove that the derived order of a struct whose fields have total orders is transitive and antisymmetric.

Solution

Solution of Exercise 8.8.

Transitivity. Let a<ba < b and b<cb < c, with ii the first index where aa and bb differ and jj the first where bb and cc differ, and m=min⁡(i,j)m = \min(i, j). For k<mk < m, a.fk=b.fk=c.fka.f_k = b.f_k = c.f_k. At mm: if i<ji < j, a.fm<b.fm=c.fma.f_m < b.f_m = c.f_m; if j<ij < i, a.fm=b.fm<c.fma.f_m = b.f_m < c.f_m; if i=ji = j, a.fm<b.fm<c.fma.f_m < b.f_m < c.f_m, and the field order is transitive. In every case mm is the first index where aa and cc differ, and a.fm<c.fma.f_m < c.f_m: a<ca < c. Antisymmetry. If a≤ba \le b, b≤ab \le a and a≠ba \ne b, at the first index ii where they differ both a.fi<b.fia.f_i < b.f_i and b.fi<a.fib.f_i < a.f_i, impossible for a total order on the field.

Exercise 8.9 ★★

Write a trait Shape with area, perimeter and name, three shapes, and a function that sorts a Vec<Box<dyn Shape>> by decreasing area and returns the names. Why can you not derive Ord on Box<dyn Shape>, and what do you use instead?

Solution

Solution of Exercise 8.9.

/// The names, largest area first.
pub fn by_area(shapes: &mut [Box<dyn Shape>]) -> Vec<String> {
    shapes.sort_by(|a, b| b.area().total_cmp(&a.area()));
    shapes.iter().map(|s| s.name()).collect()
}
Sorting trait objects by area code/bachelor-2/08-rust-traits-and-generics/exercises/shapes.rs

derive needs the fields of a type, and dyn Shape has none known; areas are f64, with no Ord. A comparator given to sort_by, here with total_cmp and the operands swapped for a decreasing order, says what is meant. The test sorts a rectangle, a circle and the 3-4-5 triangle.

Exercise 8.10 ★★★

Write a trait Numeric (Copy, +, *, a zero and a one) and a square matrix type generic over it, with identity, mul and pow by repeated squaring. Implement Numeric for i64, f64, and for booleans with or as addition and and as multiplication: why must you use a newtype for the last one? Check that the tenth power of (1110)\bigl(\begin{smallmatrix}1&1\\1&0\end{smallmatrix} \bigr) contains the Fibonacci number 55, and what the boolean powers of a graph’s adjacency matrix tell.

Solution

Solution of Exercise 8.10.

pub trait Numeric: Copy + Add<Output = Self> + Mul<Output = Self> {
    fn zero() -> Self;
    fn one() -> Self;
}
The trait code/bachelor-2/08-rust-traits-and-generics/exercises/matrix.rs

Add and bool are both defined outside our crate, so impl Add for bool breaks the orphan rule; the newtype Reach(bool) is ours. pow squares the base and multiplies it into the result for each set bit of the exponent: O(log⁡e)O(\log e) products. By induction, (1110)n=(Fn+1FnFnFn−1)\bigl(\begin{smallmatrix}1&1\\1&0\end{smallmatrix} \bigr)^n = \bigl(\begin{smallmatrix}F_{n+1}&F_n\\F_n&F_{n-1}\end{smallmatrix}\bigr), so the tenth power holds F10=55F_{10} = 55. For the boolean matrix of a graph, entry (i,j)(i, j) of the kk-th power is true exactly when a walk of kk edges leads from ii to jj; the test’s path 0→1→20 \to 1 \to 2 has one walk of length two and none of length three.

Exercise 8.11 ★★★

A program has mm types, each implementing kk traits, the trait ii having nin_i methods, all used as trait objects. (a) How many vtables does it hold, and how many words in all, if each table has three words (drop, size, alignment) plus one per method? (b) A C++ program with the same mm classes, each deriving from the kk abstract bases: how many table pointers does each object carry? (c) Which design costs memory per object, and which per type?

Solution

Solution of Exercise 8.11.

(a) One vtable per (type, trait) pair: kmkm tables, with m∑i(3+ni)=3km+m∑inim \sum_i (3 + n_i) = 3km + m \sum_i n_i words in all, stored once in the program. (b) In the usual C++ layout, an object of a class with kk polymorphic bases carries one table pointer per base subobject: kk words in each object (the first base’s may be shared with the class’s own). (c) Rust pays per type, in tables, and per trait-object pointer, one extra word; the values themselves carry nothing. C++ pays per object, kk words in every one, even when no virtual call is ever made.

Exercise 8.12 ★★★

Write Connection<State>, where State is Closed or Open, two empty types: new gives a closed connection, open consumes it and returns an open one, send exists only on Connection<Open>, and close returns a closed one. Show that sending on a closed connection, or using a connection after closing it, does not compile, and that the state costs no byte.

Solution

Solution of Exercise 8.12.

pub struct Connection<State> {
    pub sent: Vec<String>,
    _state: PhantomData<State>, // no data: the state lives only in the type
}

impl Connection<Closed> {
    pub fn new() -> Self {
        Connection { sent: Vec::new(), _state: PhantomData }
    }
    pub fn open(self) -> Connection<Open> {
        Connection { sent: self.sent, _state: PhantomData } // consumes the closed connection
    }
}

impl Default for Connection<Closed> {
    fn default() -> Self {
        Self::new()
    }
}

impl Connection<Open> {
    pub fn send(&mut self, msg: &str) {
        self.sent.push(msg.to_string());
    }
    pub fn close(self) -> Connection<Closed> {
        Connection { sent: self.sent, _state: PhantomData }
    }
}
The typestate connection code/bachelor-2/08-rust-traits-and-generics/exercises/typestate.rs

send is defined only for Connection<Open>: on a new connection it fails with E0599, no method found; after let d = c.close();, c.send("x") fails with E0382, use of a moved value, since close consumed c. PhantomData<State> has size zero, and Closed and Open have no fields: the test checks that a connection is exactly the size of its Vec<String>.

8.7 Problem: A units library

Problem 8.1

Weekend problem — A units library

On 23 September 1999 a spacecraft sent to orbit Mars was lost as it arrived. The investigation board found that a ground program wrote the impulses of the thrusters in pound-force seconds, where the interface specification required newton-seconds; the navigation software read the numbers as newton-seconds, and underestimated the effect of the thrusters by a factor of 4.45. The reconstructed trajectory passed 57 km above the surface, too low to survive. Both programs passed numbers, and a number does not carry its unit. This problem makes the unit part of the type and checks what it costs.

Part I — Newtypes.

#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct Metres(pub f64);
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct Seconds(pub f64);
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct MetresPerSecond(pub f64);

impl Add for Metres {
    type Output = Metres;
    fn add(self, o: Metres) -> Metres { Metres(self.0 + o.0) }
}
impl Add for Seconds {
    type Output = Seconds;
    fn add(self, o: Seconds) -> Seconds { Seconds(self.0 + o.0) }
}
impl Div<Seconds> for Metres {
    type Output = MetresPerSecond; // a length over a time is a speed
    fn div(self, t: Seconds) -> MetresPerSecond { MetresPerSecond(self.0 / t.0) }
}
impl Mul<Seconds> for MetresPerSecond {
    type Output = Metres; // a speed times a time is a length
    fn mul(self, t: Seconds) -> Metres { Metres(self.0 * t.0) }
}
Listing 8.16. Three units and four operations code/bachelor-2/08-rust-traits-and-generics/listings/units.rs
  1. What is the size of Metres? Of (Metres, Seconds)?
  2. Why is the field pub, and what would be lost if it were private? What would be gained?
  3. Which traits do the three types derive, and why not Eq or Ord?
  4. Could the board’s bug have been written with these types, if the impulse were a type NewtonSeconds? What would the ground program have had to write?
  5. Write a type PoundForceSeconds and a conversion From<PoundForceSeconds> for NewtonSeconds.
  6. Why is a conversion function safer than a constant 4.45 multiplied in by each caller?

Part II — Operator traits.

$ rustc --edition 2021 -O units.rs -o units && ./units
Metres(1650.0) in Seconds(1155.0): 1.43 m/s, so Metres(5142.857142857143) in an hour
$ rustc --edition 2021 units_mix.rs 2>&1 | grep -E '^(error|  -->)'
error[E0308]: mismatched types
  --> units_mix.rs:10:21
error[E0308]: mismatched types
  --> units_mix.rs:11:20
error: aborting due to 2 previous errors
Output 8.13. The library at work, and two mistakes refused (units_mix.rs).
The operations the types allow. The arrow from MetresPerSecond leads, through a multiplication by Seconds, back to Metres; every operation not drawn is a compile error.
The operations the types allow. The arrow from MetresPerSecond leads, through a multiplication by Seconds, back to Metres; every operation not drawn is a compile error.
  1. Which impl makes d / t compile, and what is the type of the result?
  2. Why does Metres * Metres not compile? Should it, and with which output type?
  3. The two errors of units_mix.rs are both mismatched types. Explain each.
  4. v * Seconds(3600.0) works but Seconds(3600.0) * v does not. Add the missing impl.
  5. Implement std::iter::Sum for Metres, so that legs.iter().map(|l| l.0).sum() gives Metres.
  6. Why is Display implemented for MetresPerSecond but Debug printed for the others in the output?

Part III — Generics over units.

  1. Write fn total<U: Add<Output = U> + Copy>(xs: &[U], zero: U) -> U, and use it on lengths and on times.
  2. How many copies of total does your program then contain?
  3. Can total be called on a slice that mixes Metres and Seconds? Why is that a feature?
  4. A trait Unit with an associated constant SYMBOL: &'static str lets one generic Display serve every unit. Sketch it.
  5. What would a trait object &dyn Unit cost compared with the generic?
  6. Name two units that a real library would add, and the operations between them.

Part IV — Zero cost.

#[no_mangle]
pub fn trip_speed_typed(legs: &[(Metres, Seconds)]) -> MetresPerSecond {
    let (mut d, mut t) = (Metres(0.0), Seconds(0.0));
    for &(dist, time) in legs {
        d = d + dist;
        t = t + time;
    }
    d / t
}

#[no_mangle]
pub fn trip_speed_raw(legs: &[(f64, f64)]) -> f64 {
    let (mut d, mut t) = (0.0, 0.0);
    for &(dist, time) in legs {
        d += dist;
        t += time;
    }
    d / t
}
Listing 8.17. The same trip, typed and untyped code/bachelor-2/08-rust-traits-and-generics/listings/units_asm.rs
$ rustc --edition 2021 --crate-type lib -C opt-level=3 --emit obj units_asm.rs
$ objdump -t units_asm.o | grep -o 'F .text.trip.*'
F .text.trip_speed_raw	00000000000000bd trip_speed_raw
F .text.trip_speed_raw	00000000000000bd trip_speed_typed
$ objdump -d --no-show-raw-insn -M intel --disassemble=trip_speed_raw units_asm.o | grep -P '^ +[0-9a-f]+:' | cut -f2- > body.txt
$ wc -l < body.txt
53
$ grep -c addpd body.txt
9
$ tail -3 body.txt
unpckhpd xmm1,xmm0
divsd  xmm0,xmm1
ret    
Output 8.14. The object file’s symbols, and the size of the code.
  1. What does the attribute no_mangle change, and why is it used here?
  2. Read the two symbol lines: what do the section, the size and the address say about the two functions?
  3. How many instructions does the function have, and what are its last three doing?
  4. Nine addpd instructions add two f64 at once. What is being added in pairs?
  5. What would have to differ in the typed version for the two to compile differently?
  6. State the result of the problem.
Solution

Solution of Problem 8.1.

1. 8 bytes, as an f64; the pair 16.

2. Other modules can build Metres(400.0) and read d.0. A private field would force a constructor and accessors: the library could then refuse a negative or NaN length, and code could not take the bare number out without saying so.

3. Debug, Clone, Copy, PartialEq, PartialOrd. A derive requires the trait of every field, and f64 has no Eq or Ord.

4. Not silently. With the interface typed NewtonSeconds, the ground program would have had to wrap its number, NewtonSeconds(x), at the point where it knew it held pound-force seconds; if its own values were typed PoundForceSeconds, passing them would be a compile error. Types check how values flow, not the first wrapping of a bare number: they move the risk to one place, where it can be reviewed.

5. A newtype PoundForceSeconds over an f64, and an implementation of From that turns it into NewtonSeconds, whose from multiplies by the number of newtons in a pound-force, the factor that the board rounded to 4.45.

6. It is written and checked once; a caller can neither forget it nor apply it twice, and .into() says that a conversion happens.

7. impl Div<Seconds> for Metres, with Output = MetresPerSecond.

8. No impl Mul for Metres exists. A library with areas would add one, with Output = SquareMetres.

9. Line 10: Add for Metres takes a Metres on the right, and t is Seconds. Line 11: d is Metres, the declared type f64; a newtype does not convert by itself.

10. impl Mul<MetresPerSecond> for Seconds { type Output = Metres; ... }, with the body Metres(self.0 * v.0).

11. impl std::iter::Sum for Metres, whose sum takes an iterator of Metres and folds it with + from Metres(0.0).

12. Only MetresPerSecond has a Display impl, used by {v}; the others are printed with {:?}, the derived Debug, which shows the type’s name: Metres(1650.0).

13. The body is xs.iter().fold(zero, |acc, &x| acc + x); total(&dists, Metres(0.0)) and total(&times, Seconds(0.0)).

14. Two, total::<Metres> and total::<Seconds>, by Proposition 8.5, unless inlined.

15. No: a slice has one element type. Adding lengths to times is exactly the mistake the types exist to refuse.

16. A trait Unit with const SYMBOL: &'static str, empty types M and S implementing it, a type Quantity<U> holding an f64 and a PhantomData<U>, and one generic implementation of Display for Quantity<U>, with U: Unit, that writes the value and U::SYMBOL. (A blanket impl<U: Unit> Display for U is refused by coherence.)

17. A trait with an associated constant is not dyn compatible; with a method symbol(&self) instead, each value would be reached through a 16-byte fat pointer and each call would go through a table, with no inlining, where the generic costs nothing.

18. For instance kilograms and newtons, with Kilograms * MetresPerSecondSquared = Newtons and Newtons * Seconds = NewtonSeconds, the board’s unit.

19. The symbol is the plain function name instead of a mangled name that encodes the crate and the path, so objdump can be given trip_speed_raw by name.

20. Both names are in the section .text.trip_speed_raw, at the same address, with the same size 0xbd, 189 bytes: one body with two names. The compiler compiled the two functions, found them identical, and kept one copy.

21. 53. unpckhpd moves the total time from the high half of a register to the low half of another, divsd divides the total distance by it, and ret returns with the result in xmm0.

22. A leg is 16 bytes, a distance and a time: one addpd adds a whole leg to the running pair (d,t)(d, t). The main loop handles eight legs per turn, eight addpd; the ninth is in the loop for the remaining legs.

23. Extra work in the operator impls, a check or a conversion, or a layout that differs from f64. The newtypes have neither: their add and div inline to the bare operations on the one field.

24. Identical machine code: the units cost nothing. The typed function is not merely as fast as the untyped one; it is the same 189 bytes of code.

Termos definidos neste capítulo

Ver todos os 1050 termos do glossário