Defining the Pet
Part of the Object Oriented Programming section of Coddy's Rust journey — lesson 19 of 61.
Challenge
EasyWelcome to the Virtual Pet project! Over the next few lessons, you'll build a complete pet simulation that brings together everything you've learned about structs, methods, modules, and encapsulation.
Let's begin building your Virtual Pet! In this first step, you'll set up the foundation by creating a Pet struct in its own module with proper encapsulation.
You'll organize your code across two files:
pet.rs: Define yourPetstruct with three private fields:name(String),energy(u32), andhunger(u32). Implement a publicnewassociated function that takes a name and creates a pet withenergyset to100andhungerset to0. Also add a publicnamegetter method that returns a reference to the pet's name.main.rs: Declare thepetmodule and bringPetinto scope. Read a name from input, create a new pet with that name, and print a welcome message.
Your welcome message should follow this format:
Welcome, {name}!For example, if the input is Buddy, the output should be:
Welcome, Buddy!Remember that the struct should be public so it can be used from main.rs, but the fields should remain private—only accessible through the methods you provide.
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();
// TODO: Create a new Pet with the given name
// TODO: Print the welcome message using the pet's name getter
// Format: "Welcome, {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