Start learning free

LESSON 605 OF 642 · OBJECT-ORIENTED PROGRAMMING

Custom Greeting in Rust

Practice

You build three greeters that greet people.

Rust has no classes, so the three share a trait, Greet.

The trait gives greet(name) a default body. Greeter keeps that default.

PirateGreeter and FormalGreeter override it. Each writes its own greet in its impl block.

  • 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 Rust

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