0
0
Rustprogramming~30 mins

Module visibility in Rust - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding Module Visibility in Rust
📖 Scenario: You are building a small Rust project that organizes code into modules. You want to control which parts of your code are visible outside their modules, just like how you might decide which rooms in a house are open to guests.
🎯 Goal: Learn how to use pub to make modules and functions visible outside their module, and how to keep some parts private.
📋 What You'll Learn
Create a module named kitchen with a private function
Create a module named living_room with a public function
Use pub keyword to control visibility
Call the public function from living_room in main
Try to call the private function from kitchen in main and observe the error
💡 Why This Matters
🌍 Real World
In real Rust projects, controlling module visibility helps keep code clean and prevents accidental use of internal details.
💼 Career
Understanding module visibility is essential for writing maintainable Rust code in professional software development.
Progress0 / 4 steps
1
Create the kitchen module with a private function
Create a module called kitchen with a function named cook_food that prints "Cooking food...". Do NOT use pub before the function, so it stays private.
Rust
Hint

Remember, functions are private by default in Rust modules unless you add pub.

2
Create the living_room module with a public function
Add a module called living_room with a function named watch_tv that prints "Watching TV...". Make this function public by adding pub before it.
Rust
Hint

Use pub fn to make the function visible outside the module.

3
Call the public function from living_room in main
Write a main function that calls the public function watch_tv from the living_room module.
Rust
Hint

Use the full path living_room::watch_tv() to call the public function.

4
Try to call the private function from kitchen in main and observe the error
In the main function, add a call to kitchen::cook_food(). Run the program and observe the error message about visibility.
Rust
Hint

This will cause a compile error because cook_food is private. This shows how Rust controls module visibility.