Consider the following Rust code. What will it print when run?
mod outer {
pub mod inner {
pub fn greet() {
println!("Hello from inner module!");
}
}
}
fn main() {
outer::inner::greet();
}Check which modules and functions are marked pub to be accessible outside.
The inner module and its function greet are both pub, so calling outer::inner::greet() works and prints the message.
What error will this Rust code produce when compiled?
mod outer {
mod inner {
pub fn greet() {
println!("Hello from inner module!");
}
}
}
fn main() {
outer::inner::greet();
}Remember that modules are private by default unless marked pub.
The inner module is private because it lacks pub. So outer::inner::greet() is inaccessible, causing a privacy error on the module.
Given this Rust code, why does it fail to compile?
mod outer {
pub mod inner {
fn greet() {
println!("Hello from inner module!");
}
}
}
fn main() {
outer::inner::greet();
}Check the visibility of the function greet inside the public module.
The module inner is public, but the function greet is private by default. So it cannot be accessed from main.
Choose the option that correctly declares a public nested module inner and a public function greet inside it.
Both the nested module and the function must be marked pub to be accessible outside.
Option D correctly marks inner as pub mod and greet as pub fn. Other options miss one or both pub keywords.
Given this Rust code, how many functions can be called from main without compilation errors?
mod outer {
pub mod inner1 {
pub fn func1() {}
fn func2() {}
}
mod inner2 {
pub fn func3() {}
pub fn func4() {}
}
pub fn func5() {}
}
fn main() {
outer::inner1::func1();
// outer::inner1::func2(); // commented
// outer::inner2::func3(); // commented
// outer::inner2::func4(); // commented
outer::func5();
}Count only functions that are pub and inside pub modules accessible from main.
inner1 is public, so func1 (pub) is accessible, but func2 is private. inner2 is private, so its functions are inaccessible. func5 is public in outer. So only func1 and func5 are accessible, total 2.