Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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?

like image 658
Fayeure Avatar asked Dec 14 '25 06:12

Fayeure


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.

like image 81
PossiblyAShrub Avatar answered Dec 16 '25 12:12

PossiblyAShrub