What is the difference between `use` and `pub use`?

Viewed 1072

there is something I don't understand in Rust's documentation: it's the pub keyword in front of use, what does it do? Here is the example from Rust's documentation (Here):

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 I can't in any case call hosting::add_to_waitlist from main, so what happens here ? what is the difference if I don't put the pub keyword ?

1 Answers

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.

Related