Why do Rust programmers use modules in their code?
Think about how you keep your desk tidy by putting things in drawers.
Modules help organize code into groups and control which parts are visible outside. This keeps code clean and easier to manage.
What is the output of this Rust code?
mod kitchen {
pub fn cook() {
println!("Cooking food");
}
fn clean() {
println!("Cleaning kitchen");
}
}
fn main() {
kitchen::cook();
// kitchen::clean(); // Uncommenting this line causes error
}Only functions marked pub can be called from outside the module.
The function cook is public and can be called from main. The function clean is private and cannot be called outside kitchen.
Why does this Rust code cause a compilation error?
mod garden {
pub fn plant() {
println!("Planting seeds");
}
}
fn main() {
plant();
}Think about how to access functions inside modules from outside.
The function plant is public but must be called with its full path garden::plant() because it is inside the module garden.
Which option contains the correct syntax to declare a module named tools with a public function hammer?
Remember the keyword to declare a module and how to mark functions public.
The correct keyword is mod. Functions are marked public with pub fn. Curly braces must enclose the module body.
Given this Rust code, how many items can be accessed from main?
mod library {
pub mod books {
pub fn read() {}
fn secret() {}
}
fn helper() {}
pub fn open() {}
}
fn main() {
// Which of these can be called here?
// library::open();
// library::helper();
// library::books::read();
// library::books::secret();
}Count only public items accessible from main.
Only library::open() and library::books::read() are public and accessible. The others are private.