Re-exporting names with pub use
is a way to make names defined in one module available in another module. This can be useful for a number of reasons, such as:
- To create a more convenient public API for your crate.
- To hide the internal structure of your crate from consumers.
- To avoid name conflicts with other crates.
To re-export a name, you simply use the pub use
keyword followed by the name of the item to be re-exported. For example, the following code re-exports the add_to_waitlist
function from the front_of_house::hosting
module:
pub use crate::front_of_house::hosting::add_to_waitlist;
Once this code is compiled, consumers of your crate will be able to call the add_to_waitlist
function directly, without having to specify the full path to the function.
Example
The following example shows how to re-export a name from one module to another:
mod front_of_house {
pub mod hosting {
pub fn add_to_waitlist() {}
}
}
pub use crate::front_of_house::hosting::add_to_waitlist;
pub fn eat_at_restaurant() {
add_to_waitlist();
}
Before the pub use
statement was added, consumers of this crate would have to call the add_to_waitlist
function using the following path:
restaurant::front_of_house::hosting::add_to_waitlist();
After the pub use
statement was added, consumers of this crate can simply call the add_to_waitlist
function directly:
add_to_waitlist();
Benefits of Re-exporting
Re-exporting names can have a number of benefits, including:
- Convenience: Re-exporting can make your crate's public API more convenient to use for consumers. For example, if you have a number of functions defined in a single module, you can re-export them all to the root of your crate, making it easier for consumers to find and use them.
- Modularity: Re-exporting can help to hide the internal structure of your crate from consumers. This can make your crate more modular and easier to maintain. For example, if you change the internal structure of your crate, you can simply re-export the names that consumers need to use, without having to break their code.
- Name conflict resolution: Re-exporting can help to resolve name conflicts with other crates. For example, if two crates define a function with the same name, you can re-export the function from the crate that you want to use.