skip to content

How does `pub use` let a Rust library expose `geometry::Point` and a `geometry::prelude` when `Point` is defined deep inside a private module?

level: middleimportance: must knowfreq 55%

answer

  1. public path versus definition path
  2. re-export at the crate root
  3. the item itself must be pub
  4. prelude module of re-exports

basics

~20 s

A pub use at the crate root, such as pub use shapes::point::Point, publishes the item as geometry::Point while it stays defined in a private module. A pub mod prelude of re-exports gives users one glob import.

solid answer

~40 s

`use` binds a name to an item; `pub use` makes that binding part of the module's public interface, which is called a **re-export**. A library can keep a deep, private module tree (`shapes::point`, `shapes::circle`) and still publish flat paths: `pub use self::shapes::point::Point;` at the root makes `geometry::Point` the public path, while `geometry::shapes::point::Point` fails outside the crate with E0603 because `shapes` is private. It is one type with two paths, not a copy. The item itself must be `pub`: re-exporting a `pub(crate)` item fails with E0364. A `pub mod prelude` that re-exports the common types and traits lets users write `use geometry::prelude::*;`, and the traits put their methods in scope. Internals can then move freely as long as the re-exports keep pointing at the items.

code

rust · 32 lines
rust
// `mod geometry` stands in for the library crate's root.
mod geometry {
    mod shapes {
        pub mod point {
            pub struct Point { pub x: f64, pub y: f64 }
        }
        pub mod circle {
            pub struct Circle { pub center: super::point::Point, pub r: f64 }
        }
    }
    mod measure {
        pub trait Area { fn area(&self) -> f64; }
        impl Area for crate::geometry::Circle {
            fn area(&self) -> f64 { 3.14159 * self.r * self.r }
        }
    }
    // The public API: flat paths over a deep private tree.
    pub use self::shapes::circle::Circle;
    pub use self::shapes::point::Point;
    pub mod prelude {
        pub use super::measure::Area;
        pub use super::{Circle, Point};
    }
}

use geometry::prelude::*;

fn main() {
    let c = Circle { center: Point { x: 1.0, y: 2.0 }, r: 2.0 };
    let same: &geometry::Point = &c.center; // one type, two paths
    println!("area = {:.2}, center = ({}, {})", c.area(), same.x, same.y);
}

go deeper

for a junior

Know that pub use makes an imported name public, so users can write a short path such as geometry::Point.

for a middle

Explain why the long path fails with E0603 outside the crate, why a pub(crate) item cannot be re-exported (E0364), and what a prelude module is for.

for a senior

Design the crate root as the public table of contents, put method-bearing traits in the prelude, and check that every type in a public signature is nameable by users.

for a principal

The tradeoff is how much a prelude glob should carry: convenience for users against collisions and the forward-compatibility hazard that each added name brings.

## What `pub use` binds A `use` declaration creates a local name for an item that lives at another path. By default that name is private to the module that declares it. Marking it `pub` makes the binding part of that module's public interface: anyone who can see the module can name the item through it. The Reference calls this a **re-export**, and it can redirect a public name to a definition whose own path is private. Nothing is copied. `geometry::Point` and the definition at `geometry::shapes::point::Point` are one struct: same type, same impls, same trait implementations. A value built through one path is accepted wherever the other is expected. ## Flattening a deep internal tree A geometry library often grows a tree that suits its maintainers rather than its users: | Defined at (private) | Re-exported as (public) | |---|---| | `geometry::shapes::point::Point` | `geometry::Point` | | `geometry::shapes::circle::Circle` | `geometry::Circle` | | `geometry::measure::Area` (trait) | `geometry::prelude::Area` | With `mod shapes` and `mod measure` left private and `pub use` lines at the crate root, the right-hand column is the whole public API. Three consequences follow: - A dependent crate that writes the long path gets **E0603**, "module `shapes` is private", and rustc's help suggests the public re-export instead. - Maintainers can split `shapes::point` into two files or move `Circle` to another module without a breaking change, provided the `pub use` lines are updated to point at the new location. - rustdoc **inlines** a public item re-exported from a private module, so the documentation shows `Point` at the crate root as if it were defined there. A re-export from a public module is listed as a re-export unless it carries `#[doc(inline)]`. ## The rules rustc enforces 1. **The item must be visible enough.** `pub use` cannot widen visibility. With `mod shapes { pub(crate) struct Point; }`, the line `pub use shapes::Point;` fails with **E0364**: "`Point` is only public within the crate, and cannot be re-exported outside". The struct has to be `pub`; its module can stay private. 2. **Both namespaces come along.** Re-exporting a tuple or unit struct carries its type and its constructor, so a tuple-struct `Point` could be built as `geometry::Point(1.0, 2.0)` through the re-export. 3. **Renames are allowed.** `pub use self::shapes::point::Point as Vec2;` publishes the item under a different name; keeping an old name alive this way after a rename is a technique the material on API evolution covers. ## The prelude pattern A **prelude module** is an ordinary public module whose only content is re-exports of what most users need: ```rust pub mod prelude { pub use super::measure::Area; pub use super::{Circle, Point}; } ``` Users then write `use geometry::prelude::*;`. Guidance that keeps a prelude useful: - Include the **traits** whose methods users call. A method from a trait is callable only when the trait is in scope, so a prelude that re-exports `Area` makes `circle.area()` work after one import. - Include the handful of types nearly every user touches; leave rare types at their normal public paths. - Avoid names that collide with the standard library or common crates (`Result`, `Error`): a glob that brings them in quietly shadows the user's prelude names. - Remember that nothing about the name is special. Only the standard library's prelude is injected automatically; a library's `prelude` module must be imported explicitly. Growing a prelude has a compatibility side: a new trait arriving through a user's glob import can make a method call ambiguous. Cargo's SemVer guide counts adding public items as a minor change and names glob imports as a known hazard; release policy belongs to the lesson on API evolution. ## Reading a crate's API When reviewing a library, its root module's `pub use` lines and its `prelude` module *are* the public API. A useful check is that every type appearing in a public signature is reachable through one of those paths, so users can name what they receive. The crate root then reads like a table of contents while the implementation stays organised for the people who maintain it. Two shortcuts deserve a second look in review: - A **glob re-export** such as `pub use self::shapes::*;` publishes every public item of `shapes` at once. It is quick, but every public item later added to `shapes` silently joins the crate's root API, so the public surface stops being something anyone chose. - A **re-exported module**, `pub use self::shapes::circle;`, publishes the module path `geometry::circle` and everything public inside it, which is coarser than re-exporting the individual types.

  • Is the re-exported `geometry::Point` a different type from the struct defined in `shapes::point`?
    No. `pub use` binds another name for the same item, so both paths denote one type with the same impls and trait implementations. A value built through `geometry::Point` is accepted by a function that names the long path inside the crate, and vice versa.
  • Why does `pub use shapes::Point;` fail with E0364 when `Point` is declared `pub(crate)`?
    A re-export cannot make an item more visible than its own declaration. `pub(crate)` caps `Point` at the crate, so publishing it beyond the crate is rejected. Declaring the struct `pub` fixes it while its module `shapes` stays private; the private module is what keeps the long path unusable outside.
  • How does rustdoc show `pub use shapes::point::Point` when `shapes` is private?
    It inlines the item: `Point` and its documentation appear at the crate root as if defined there, because users cannot reach the private module. A re-export of an item from a public module is listed as a re-export line unless you add `#[doc(inline)]`.

A re-export works like an organisation's public mailing address: the mailroom forwards each letter to whichever office currently handles it, so offices can move between floors without anyone outside updating an address book.

  • pub use copies the type, so the two paths name distinct types.
  • Re-exporting needs every intermediate module marked pub.
  • pub use can widen a pub(crate) item into the public API.
  • A library's prelude module is imported automatically, like std's.
  • Moving a definition always breaks users, even with an updated re-export.