Menu
Coddy logo textTech

Recap - Zoo Manager

Part of the Object Oriented Programming section of Coddy's Rust journey — lesson 48 of 61.

challenge icon

Challenge

Easy

Let's build a zoo manager that brings together all the trait object concepts you've learned! You'll create a system where different animals—each with their own unique sound—can be stored in a single collection and made to speak one by one.

You'll organize your code across two files:

  • animals.rs: Define a public Speak trait with a speak method that takes &self and returns a String. Then create three public structs—Dog, Cat, and Bird—each with a public name field (String). Implement the Speak trait for each animal with their characteristic sounds:
    • Dog should return {name} says: Woof!
    • Cat should return {name} says: Meow!
    • Bird should return {name} says: Tweet!
  • main.rs: Bring in your animals module and create a zoo! Build a Vec<Box<dyn Speak>> containing one of each animal type using the provided inputs. Add them in order: Dog first, then Cat, then Bird. Finally, iterate through your zoo and print each animal's sound on its own line.

This challenge demonstrates the real power of trait objects—three completely different animal types living together in one collection, each responding to the same speak() call with their own unique behavior.

Your output should display each animal speaking in order:

{dog_name} says: Woof!
{cat_name} says: Meow!
{bird_name} says: Tweet!

For example, with inputs Rex, Whiskers, and Tweety:

Rex says: Woof!
Whiskers says: Meow!
Tweety says: Tweet!

You will receive three inputs: the dog's name, the cat's name, and the bird's name.

Try it yourself

mod animals;

use animals::{Speak, Dog, Cat, Bird};

fn main() {
    // Read input for animal names
    let mut dog_name = String::new();
    std::io::stdin().read_line(&mut dog_name).expect("Failed to read line");
    let dog_name = dog_name.trim().to_string();

    let mut cat_name = String::new();
    std::io::stdin().read_line(&mut cat_name).expect("Failed to read line");
    let cat_name = cat_name.trim().to_string();

    let mut bird_name = String::new();
    std::io::stdin().read_line(&mut bird_name).expect("Failed to read line");
    let bird_name = bird_name.trim().to_string();

    // TODO: Create a Vec<Box<dyn Speak>> called zoo
    // Add animals in order: Dog first, then Cat, then Bird

    // TODO: Iterate through the zoo and print each animal's sound
}

All lessons in Object Oriented Programming