Menu
Coddy logo textTech

Feeding the Pet

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

challenge icon

Challenge

Easy

Now that your pet exists, it's time to give it the ability to eat! In this step, you'll add a feed method that lets you take care of your pet's hunger.

Building on your existing pet.rs module, add a feed method that decreases the pet's hunger level. When fed, the pet's hunger should decrease by 30, but it should never go below 0. After feeding, the method should print a message showing the pet enjoyed its meal.

You'll also need a hunger getter method so you can check the pet's hunger level from outside the module.

In main.rs, you'll read the pet's name and an initial hunger value. Create your pet, set its initial hunger, feed it once, and then display the updated hunger level.

The output should follow this format:

{name} enjoyed the meal!
Hunger: {hunger_level}

For example, if the input is:

Buddy
50

The output should be:

Buddy enjoyed the meal!
Hunger: 20

And if the hunger starts at 20, feeding would bring it to 0 (not negative):

Buddy enjoyed the meal!
Hunger: 0

You'll need to add a set_hunger method to initialize the hunger for testing purposes, since the new constructor sets hunger to 0 by default.

Try it yourself

mod pet;

use pet::Pet;

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

    let my_pet = Pet::new(name);

    println!("Pet name: {}", my_pet.name());
}

All lessons in Object Oriented Programming