Exposing a different structure with `pub use`

In section 7.4, The Book states:

With pub use, we can write our code with one structure but expose a different structure.

Could someone provide an example of using pub use to create an alternate structure? I'm having trouble understanding what exactly it's talking about without one. Thanks!

By structure here, they're talking about the hierarchy of modules (not a struct). Let me contrive a different example, maybe I have a

pub mod shapes {
    mod ovoids { /* circles, spheres, ... */ }
    mod sharps { /* squares, cubes, tesseracts, ... */ }
   // ...

But my typical consumers deal with specific sets of dimensions, so I export

    pub mod two_d {
        pub use crate::ovoids::circle;
        pub use crate::sharps::square;
    }
    pub mod three_d {
        pub use crate::ovoids::sphere;
        pub use crate::sharps::cube;
    }
    // ...
}

Then when developing, I see a "structure" organized by sharpness or whatever (in the private modules / where the code actually lives), while consumers of my crate see a structure organized by the number of dimensions (the public re-exports).

6 Likes

Fantastic example. Thank you so much for taking the time to reply!

So, if I'm understanding correctly, consumers of the two_d module would use circle as two_d::circle instead of ovoids::circle. Is that correct?

Correct -- and in this example (and the one in the book), consumers don't get a choice. The re-exports are the only paths visible, because they're re-exporting from non-pub paths. mod ovoids is private so they can't name ovoids::circle directly.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.