Start learning free

LESSON 610 OF 639 · OBJECT-ORIENTED PROGRAMMING

Printable Things in Go

Practice

You write an interface and two structs that use it.

Printable is an interface with one method, label(). It returns a short text about the item.

Two structs implement it:

  • NewBook(title, author) builds a Book. Its label is the title, then by, then the author.
  • NewTicket(code) builds a Ticket. Its label is Ticket, then the code.

One space separates the words of a label.

Go needs no implements word. A struct with a label() string method is a Printable.

Then write printAll(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 constructors. The harness prints each label on its own line.

 

Example 1:

Input: NewBook("Dune", "Herbert"), NewTicket("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: NewTicket("B7"), NewTicket("C3"), NewBook("Emma", "Austen")
Output:
Ticket B7
Ticket C3
Emma by Austen

Explanation: The labels keep the order of the items.

Example 3:

Input: NewBook("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

    Printable Things in Go

    Keep going with Go500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free