Start learning free

LESSON 602 OF 639 · OBJECT-ORIENTED PROGRAMMING

Custom Greeting in Go

Practice

You build three structs that greet people.

Greeter is the plain one. PirateGreeter and FormalGreeter embed Greeter, as in the Inheritance lesson.

Each struct has a method greet(name). The two children declare their own greet. It overrides (shadows) the one they got from Greeter.

  • In Greeter, greet(name) returns "Hello, <name>".
  • In PirateGreeter, it returns "Ahoy, <name>!".
  • In FormalGreeter, it returns "Good day, <name>.".

Each input line is a kind of greeter, then a person's name. The kinds are greeter, pirate and formal.

For each line, the test code makes that greeter and prints what greet(name) returns.

 

Example 1:

Input:
    greeter Ann
    pirate Bob
    formal Cy
Output:
    Hello, Ann
    Ahoy, Bob!
    Good day, Cy.
Explanation: Each greeter answers with its own version of greet.

Example 2:

Input:
    pirate Mia
    formal Mia
    greeter Mia
Output:
    Ahoy, Mia!
    Good day, Mia.
    Hello, Mia
Explanation: The same name gets three different greetings.

Example 3:

Input:
    formal Lee
    pirate Jack
    formal Max
Output:
    Good day, Lee.
    Ahoy, Jack!
    Good day, Max.
Explanation: No plain greeter here.
Each line still gets its own greeting.

 

Constraints:

  • A name is one word of 1 to 20 English letters.
  • 1 to 100 lines per test case.
STEP 1 OF 6
    Ctrl + Enter to check

    Custom Greeting 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