What is the usage of `pub use` and what is the difference between it and `use`?

Perhaps the example I gave is not very appropriate.

code A:

mod my_module {
    pub mod sub_module {
        pub fn func() {
            println!("hello");
        }
    }
}

use my_module::sub_module::func;

fn main() {
    func();
}

code B:

mod my_module {
    pub mod sub_module {
        pub fn func() {
            println!("hello");
        }
    }
}

pub use my_module::sub_module::func;

fn main() {
    func();
}

According to my inappropriate example,there is no difference between code A and code B.

It can be used to re-export things under a different name:

mod my_module {
    pub use sub_module::func;
    pub mod sub_module {
        pub fn func() {
            println!("hello");
        }
    }
}

use my_module::func;

fn main() {
    func();
}

This doesn't compile if you remove pub from pub use.

3 Likes

Something I've seen pub use used for often is for library crates that use another crate's types as part of their interface. For example, the axum crate does a pub use http, re-exporting the http crate. By doing this, Axum can offer/control their interface; they don't force the end user to import http and match compatibility with the version Axum is using. They get the benefit of using third-party code while avoiding some of the headaches.

(This is my observation as an outsider to the library development, if I'm wrong in my interpretation please let me know)