Finding Your Way (use)
Last time we built rooms called modules. But how do you tell Rust exactly which room to look in? You give it directions β a path! πΊοΈ
A path is like an address. It says, βStart at the front door, go down the hall, into the
kitchen, and grab the cook function.β Letβs learn how to write these directions, plus a
handy shortcut to make them shorter.
A path is an address
A path names where something lives in your code. You spell it out with two dots ::
between each step, starting from crate (that means βthis whole crate, from the very
topβ).
crate::kitchen::cook
means: start at the top, go into the kitchen room, find cook. πΊοΈ
Writing the whole path every single time can feel long, especially if you use it a lot. Thatβs where our shortcut comes in.
The use shortcut
The word use makes a shortcut to something. After you use a path once, you can
write just the short name instead of the whole long address. π
Here we use the kitchen module, then call cook with the short name:
Thanks to use, we just wrote cook() instead of crate::kitchen::cook() every time.
Much shorter, and still easy to read! π
use the whole room,
like use crate::kitchen;, and then call kitchen::cook(). That
way you can still tell which room the code came from! π¦
pub fn bake() inside the kitchen module that prints
a baking message. Add another use line for it, then call bake()
from main. Shortcuts everywhere! π§
Quick quiz
What does use do?
Yes! use creates a shortcut, so you can call the short name instead of the long path. π
crate::kitchen::cook, and
use makes a handy shortcut so you can write the short name.
You've kept a big project tidy β high five! ποΈ Next world: World 8: Collections,
where we store whole groups of things together! π