There is something I don't understand in Rust's documentation: the pub keyword in front of use, what does it do?
Here is an example from Rust's documentation:
mod front_of_house {
pub mod hosting {
pub fn add_to_waitlist() {
println!("Added to waitlist");
}
}
}
pub use crate::front_of_house::hosting;
pub fn eat_at_restaurant() {
hosting::add_to_waitlist();
hosting::add_to_waitlist();
hosting::add_to_waitlist();
}
When I try to make a main to interact with this I came up with:
use tests::eat_at_restaurant;
fn main() {
eat_at_restaurant();
}
But when I remove the use keyword it does the same thing. And in any case I can't call hosting::add_to_waitlist from main, so what happens here? What is the difference if I don't put the pub keyword?
use is used to import an item into the current module,
pub use allows us to (not only import but,) re-export the item.
Here's an example where pub use is required:
// src/foo/mod.rs
mod bar;
pub use bar::item;
// src/foo/bar.rs
pub fn item() {
println!("Hello, world!");
}
// src/main.rs
mod foo;
use foo::item;
fn main() {
item();
}
If we had used a plain use then item wouldn't be accessible. However, since we added the pub keyword, item is now available to all modules that use the nested module.
We call this "re-exporting" because item isn't actually defined in foo but rather foo "re-exports" item from foo::bar.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With