πŸšͺ
World 7 Β· Keeping Things Tidy

Modules: Rooms in a House

Think about your house. 🏠 You don’t cook in the bathroom, and you don’t sleep in the kitchen! Each room has its own job, and that keeps everything tidy and easy to find.

A crate can get big, just like a house. Rust lets you split your code into rooms called modules. Each module keeps related code together, so your program stays neat and easy to read. πŸšͺ

Building a room with mod

To make a module, you use the word mod and give your room a name. Everything inside the curly braces { } belongs to that room.

mod kitchen {
    fn cook() {
        println!("Sizzle! Dinner is cooking. 🍳");
    }
}
Think of it like this… A module is a room in your house. The kitchen module holds all the cooking code, just like a real kitchen holds the pots and pans. 🍳

Opening the door with pub

Here’s a tricky part. By default, everything inside a room is private β€” the door is closed. Code outside the room can’t reach in. To open the door, you add the word pub, which is short for public.

New word pub means public. It opens the door so code outside the module can use what's inside. No pub means the door stays shut. πŸšͺ

Let’s open the kitchen door and call cook from main. We use two dots :: to walk into the room, like kitchen::cook().

See how main reached into the kitchen room and ran cook? The :: is like walking through the doorway to find what you need. πŸŽ‰

Ferris says: Forgot the pub? Then the door is locked, and Rust will gently tell you it can't find your function. Add pub and try again! πŸ¦€
Try this! Add a second room called garden with a pub fn water() that prints a watering message. Then call garden::water() from main. Two rooms, one tidy house! 🌻

Quick quiz

What does pub do for a function inside a module?

Right! pub makes the function public, so code outside the room can call it. πŸŽ‰

You learned… Modules are rooms that group related code with mod name { }, pub opens the door, and :: walks you inside to call things like kitchen::cook(). Next up: finding your way around with paths and the use shortcut! πŸ—ΊοΈ