Menu
Coddy logo textTech

Defining the Pet

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

challenge icon

Challenge

Easy

Welcome 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 your Pet struct with three private fields: name (String), energy (u32), and hunger (u32). Implement a public new associated function that takes a name and creates a pet with energy set to 100 and hunger set to 0. Also add a public name getter method that returns a reference to the pet's name.
  • main.rs: Declare the pet module and bring Pet into 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