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. π³");
}
}
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.
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. π
pub? Then the door is locked, and
Rust will gently tell you it can't find your function. Add pub and try
again! π¦
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. π
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! πΊοΈ