Skip to content

Checkpoint: Report Different Records

The Course
•
30 min study

The queue will hold more than books. An article or a single chapter can be queued too, and each needs an ID. In this checkpoint you combine today's ideas: one generic wrapper for any record, one trait for the behavior a report needs, and report functions that work for every record type with that behavior. The design question to get right is where the bound goes. The wrapper should accept anything; only the report needs titles.

What you will use

  • A generic struct. Tagged<T> pairs a u32 ID with a value of any type T.
  • A trait of your own. Title declares fn title(&self) -> &str, and Book and Article implement it.
  • A trait bound on a function. show<T: Title> borrows a &Tagged<T> and can call title on the value.
  • A slice of generic values. show_all takes &[Tagged<T>], as on Day 2, so it works with an array or a vector.

Plan before you type

  1. Declare trait Title and implement it for Book and Article, returning &self.0.
  2. Write fn show<T: Title>(record: &Tagged<T>) that prints the ID and the title.
  3. Write fn show_all<T: Title>(records: &[Tagged<T>]) that calls show for each record.
  4. In main, show the book and the article, then call show_all on an array of two articles.
  5. Build a Tagged<u32> for a page count and print its fields directly, to confirm the wrapper has no bound.
Prove the bound is where it belongs

Add T: Title to the struct, struct Tagged<T: Title>, and run. The page-count tag must now fail with E0277, because u32 has no title. That is why the bound belongs on the functions. Then try show(&pages) with the original struct: it should fail the same way, at the call.

Mistakes worth checking for

  • error[E0599]: no method named title found: show has a type parameter but no T: Title bound.
  • error[E0277]: the trait bound u32: Title is not satisfied on the page-count tag: the bound was put on the struct instead of the function.
  • show_all cannot take an array: its parameter is &Vec<Tagged<T>> instead of the slice &[Tagged<T>].
  • Mixing a book and an article in one array fails with E0308: an array holds one type, and Tagged<Book> and Tagged<Article> are different types. Show them separately.
Exercise

Your turn

Give Book and Article a common Title trait. Write show for one tagged record and show_all for a slice of them. Print #7 Rust Patterns and #9 Iterator Notes with show, then #10 Trait Basics and #11 Error Handling with show_all on an array of two articles. Finally build a Tagged<u32> with ID 7 and value 320 and print #7 has 320 pages.

Your working space Rust
struct Tagged<T> {
    id: u32,
    value: T,
}

struct Book(String);
struct Article(String);

fn main() {
    let book = Tagged { id: 7, value: Book(String::from("Rust Patterns")) };
    let article = Tagged { id: 9, value: Article(String::from("Iterator Notes")) };
    // Show both records through one function, then a slice of articles.
}
Hint 1: the idea

Only the reports need access to titles. Tagged can stay generic over any T, and each report function carries the bound itself.

Hint 2: a first step

Give show a parameter of type &Tagged<T> and require T: Title. In show_all, loop with for record in records and pass each record to show; it is already a reference.

Worked solution
Run the solution Rust
struct Tagged<T> {
    id: u32,
    value: T,
}

trait Title {
    fn title(&self) -> &str;
}

struct Book(String);
struct Article(String);

impl Title for Book {
    fn title(&self) -> &str { &self.0 }
}

impl Title for Article {
    fn title(&self) -> &str { &self.0 }
}

fn show<T: Title>(record: &Tagged<T>) {
    println!("#{} {}", record.id, record.value.title());
}

fn show_all<T: Title>(records: &[Tagged<T>]) {
    for record in records {
        show(record);
    }
}

fn main() {
    let book = Tagged { id: 7, value: Book(String::from("Rust Patterns")) };
    let article = Tagged { id: 9, value: Article(String::from("Iterator Notes")) };
    show(&book);
    show(&article);

    let reading_list = [
        Tagged { id: 10, value: Article(String::from("Trait Basics")) },
        Tagged { id: 11, value: Article(String::from("Error Handling")) },
    ];
    show_all(&reading_list);

    let pages = Tagged { id: 7, value: 320 };
    println!("#{} has {} pages", pages.id, pages.value);
}
Text
#7 Rust Patterns
#9 Iterator Notes
#10 Trait Basics
#11 Error Handling
#7 has 320 pages

The bound belongs to the functions that use the behavior, so Tagged can still wrap a page count that has no title. show_all passes the bound on to show because both name T: Title. One array still holds a single record type; holding books and articles together needs a different tool, an enum of records, or a trait object as in the advanced course. Day 4 turns to collections: ordered maps and iterators.

Was this article helpful?

Your response is saved on this device.