Start learning free

LESSON 603 OF 642 · OBJECT-ORIENTED PROGRAMMING

Animal Sounds in Rust

Practice

You build two structs, Animal and Dog.

A dog is a kind of animal. Rust has no inheritance. As in the Inheritance lesson, Dog reuses Animal by holding one.

  • Animal's new(name) returns an animal with that name.
  • describe() returns "<name> is an animal".
  • Dog has one field, animal, of type Animal.
  • Dog's new(name) builds that animal with Animal's own new.
  • Dog's describe() forwards the call to its animal. It returns the same text.
  • A dog adds one method. fetch() returns "<name> fetches the ball".

Each input line is animal or dog, then a name.

For an animal, the test code prints its describe(). For a dog, it prints describe(), then fetch(). Each text goes on its own line.

 

Example 1:

Input:
    dog Rex
    animal Tom
Output:
    Rex is an animal
    Rex fetches the ball
    Tom is an animal
Explanation: Rex is a dog. It describes itself and fetches.
Tom is a plain animal. It only describes itself.

Example 2:

Input:
    dog Max
    dog Bella
Output:
    Max is an animal
    Max fetches the ball
    Bella is an animal
    Bella fetches the ball
Explanation: Both dogs describe themselves with the method they inherited.

Example 3:

Input:
    animal Rex
    dog Rex
Output:
    Rex is an animal
    Rex is an animal
    Rex fetches the ball
Explanation: The two have the same name.
Only the dog fetches.

 

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

    Animal Sounds 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