Sub topic 6
Re-exports and Shaping a Public API
This chapter assumes you know how modules, use declarations, and pub visibility work. It covers pub use, which lets you separate where code lives from the path users type to reach it.
Why internal layout and public paths differ
Your module tree is organized for you, the maintainer. Callers care about something else: short, memorable paths. Without re-exports, the path to an item is always its definition path. A user of the my_geometry crate would have to write this:
use my_geometry::geometry::shapes::Square;That path exposes your file layout. If you later move Square into another module, every caller breaks. A re-export fixes both problems.
What `pub use` does
A plain use brings a name into scope for the current module only. It is private by default, so code outside the module cannot reach the name through it. Adding pub makes the imported name part of the module's public interface, as if the item were declared there.
// src/lib.rs
mod geometry;
pub use geometry::shapes::Square;
pub fn describe(s: &Square) -> String {
use std::fmt::Write;
let mut out = String::new();
write!(out, "square with area {}", s.area()).unwrap();
out
}Here geometry is private, so outside code cannot write my_geometry::geometry::.... The only way to reach Square is my_geometry::Square. This assumes src/geometry.rs declares pub mod shapes; and src/geometry/shapes.rs defines pub struct Square(pub u32) with a public area method, as in the previous chapter.
Two details matter here:
- The re-exported item must be visible to the module doing the re-export. You cannot re-export something private.
- The
use std::fmt::Write;insidedescribeis a function-local import. It brings theWritetrait into scope sowrite!works on aString. The import does not leak into the rest of the file.
The two layers of privacy
Making a module private and re-exporting its items gives you two independent controls:
| Declaration | Effect |
|---|---|
| `mod geometry;` | Module path is hidden from users |
| `pub mod geometry;` | Module path is public API |
| `pub use geometry::shapes::Square;` | Item is reachable at the re-export location |
| `pub(crate) use ...;` | Re-export is visible only inside your crate |
The last row is useful for internal convenience. You can build a small "prelude" for your own modules without promising anything to outside users.
Renaming and grouping re-exports
You can rename on the way out with as, which helps when two modules export the same name:
mod text {
pub struct Error;
}
mod network {
pub struct Error;
}
pub use network::Error as NetworkError;
pub use text::Error as TextError;
fn main() {
let _a = NetworkError;
let _b = TextError;
}Nested paths work as they do with use:
mod shapes {
pub struct Circle;
pub struct Square;
}
pub use shapes::{Circle, Square};
fn main() {
let _c = Circle;
let _s = Square;
}Glob re-exports
pub use module::*; re-exports every public item from a module. It is short, but it has costs:
- New public items in
modulebecome part of your API automatically, which may not be what you intended. - Two globs that bring in the same name cause an ambiguity error only when that name is used, so the problem can appear late.
- Readers cannot see from
lib.rswhat the crate offers.
Prefer explicit lists for the main API. Globs fit best for a deliberate prelude module, where "everything in here" is the point.
pub mod prelude {
pub use crate::shapes::{Circle, Square};
}
pub mod shapes {
pub struct Circle;
pub struct Square;
}Users then write use my_geometry::prelude::*; to get the common names in one line.
Designing a public API
A practical approach is to decide the public surface first, then arrange modules to support it.
- List the types and functions users need. Everything else stays private.
- Make modules private by default. Expose them with
pub modonly when the module path itself is meaningful, such asstd::collections. - Re-export the main types at the crate root so common use needs one short path.
- Keep submodules public when they group many related items. Re-exporting hundreds of names to the root hurts discoverability.
- Use
pub(crate)andpub(super)for items that other modules in your crate need but outside users do not.
Changing a public path is a breaking change under semantic versioning. Changing a private module layout is not. Re-exports are what let you keep the first stable while you change the second.
Doc comments and re-exports
Documentation is attached to the item, not to the path. cargo doc shows a re-exported item at its new location and lists it as a re-export. Doc tests (covered in a later chapter) should use the short public path, because they act like outside users:
/// Adds two numbers.
///
/// ```
/// assert_eq!(my_geometry::add(2, 3), 5);
/// ```
pub fn add(a: i32, b: i32) -> i32 {
a + b
}If add lived in a private module and was re-exported at the root, this example would still compile, and that confirms the public path works.
Common errors
- "module
geometryis private" (E0603). You tried to name a path through a private module. Either re-export the item or make the modulepub. - "
Squareis private" when re-exporting. The item itself is notpub, or it ispub(super)or narrower and cannot be seen from the re-exporting module. Widen its visibility. - "cannot glob-import a module into itself" or unexpected name clashes. Check for duplicate names from two globs, and import the one you want explicitly.
- A private type in a public signature. If a public function returns a type that is not nameable from outside, callers can use the value but cannot name its type. Re-export the type so it is nameable.
- Unused import warnings on a
pub use. Apub useat the crate root of a library is never reported as unused. In a binary crate,pub useis not part of any external API, so the compiler warns when the name is not used.
A complete example
This single-file crate shows the whole pattern in miniature. The inner module is private, and a public function and type are exposed through re-exports.
mod internal {
pub mod shapes {
#[derive(Debug)]
pub struct Rect {
pub width: u32,
pub height: u32,
}
impl Rect {
pub fn area(&self) -> u32 {
self.width * self.height
}
}
}
pub fn unit() -> shapes::Rect {
shapes::Rect { width: 1, height: 1 }
}
}
pub use internal::shapes::Rect;
pub use internal::unit;
fn main() {
let r = Rect { width: 3, height: 4 };
println!("{:?} has area {}", r, r.area());
println!("unit area {}", unit().area());
}If you later rename internal to core_types, only the two pub use lines change. Code that uses Rect and unit is untouched.
Exercise
A library has mod geometry; in src/lib.rs, and geometry contains pub mod shapes with pub struct Square. A user writes use my_geometry::geometry::shapes::Square; and gets error E0603. What single line in lib.rs lets the user write use my_geometry::Square;, and why does the user's original path still fail?
Show answer
Add pub use geometry::shapes::Square;. The original path still fails because geometry remains a private module, so its path is not accessible from outside the crate. The re-export creates a new public name for the same item at the crate root.
Exercise
You want a helper re-export that other modules in your crate can use as crate::util::Config, but you do not want it to become part of the public API. Which form do you use, and what is the risk of using a * glob for the same purpose with plain pub?
Show answer
Use pub(crate) use for the re-export. With a plain pub use ...::*, every public item added to the source module later becomes public API automatically, which can cause accidental breaking-change obligations and name clashes.