Feeding the Pet
Part of the Object Oriented Programming section of Coddy's Rust journey — lesson 20 of 61.
Challenge
EasyNow 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
50The output should be:
Buddy enjoyed the meal!
Hunger: 20And if the hunger starts at 20, feeding would bring it to 0 (not negative):
Buddy enjoyed the meal!
Hunger: 0You'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
1Methods and Behavior
Intro Implementation BlocksThe Self ParameterMutable MethodsAssociated FunctionsMultiple Implementation BlocksMethod ChainingRecap - Rectangle Actions4Project: Virtual Pet
Defining the PetFeeding the Pet7Standard Traits
The Debug TraitThe Display TraitClone and CopyEquality TraitsRecap - Printable Point10Project: Document System
The Draw TraitText Component2Encapsulation and Modules
Modules BasicsThe Public KeywordPrivate FieldsGettersSettersRecap - Secure Locker5Generics
Generic StructsGeneric MethodsMultiple Generic TypesGeneric FunctionsRecap - Coordinate Point8Traits as Bounds
Trait Bounds SyntaxMultiple BoundsThe Where ClauseReturning Types with TraitsRecap - Generic Printer11Design Patterns in Rust
Newtype PatternCompositionThe Drop TraitFrom and IntoRecap - Smart Pointer Mock