Start learning free

LESSON 650 OF 679 · OBJECT-ORIENTED PROGRAMMING

Printable Things

Practice

You write a trait and two structs that use it.

Printable is a trait with one method, label(). A trait is Rust's interface. The method returns a short text about the item.

Two structs implement it:

  • Book has a title and an author. Its label is the title, then by, then the author.
  • Ticket has a code. Its label is Ticket, then the code.

One space separates the words of a label.

Then write print_all(items). It returns every item's label, in the same order.

The items mix books and tickets. Use each one only through label().

The starter code already has the structs and their new functions. The harness prints each label on its own line.

 

Example 1:

Input: Book::new("Dune", "Herbert"), Ticket::new("A12")
Output:
Dune by Herbert
Ticket A12

Explanation: The book joins its title and author with by.
The ticket puts Ticket before its code.

Example 2:

Input: Ticket::new("B7"), Ticket::new("C3"), Book::new("Emma", "Austen")
Output:
Ticket B7
Ticket C3
Emma by Austen

Explanation: The labels keep the order of the items.

Example 3:

Input: Book::new("1984", "Orwell")
Output:
1984 by Orwell

Explanation: A title can be digits. It is still text.

 

Constraints:

  • 1 to 100 items.
  • Each title, author and code is one word.
  • A word has 1 to 20 letters or digits.
STEP 1 OF 6
    Ctrl + Enter to check