diff --git a/src/SUMMARY.md b/src/SUMMARY.md index 7b6d6cd91..e90d3716d 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -86,6 +86,7 @@ - [Creating a Library]() - [Cargo]() - [Crates.io]() + - [Organizing your Public API](chYY-YY-public-api.md) - [Documentation](chYY-YY-documentation.md) - [Workspaces and Multiple Related Crates](chYY-YY-workspaces.md) diff --git a/src/ch07-04-importing-names-with-use.md b/src/ch07-04-importing-names-with-use.md index 8d9cc967c..9b1f91f9c 100644 --- a/src/ch07-04-importing-names-with-use.md +++ b/src/ch07-04-importing-names-with-use.md @@ -142,23 +142,3 @@ src/main.rs:8 use TrafficLight::*; If, instead, we were explicit about the variants we wanted to import, our code would not have stopped compiling when we upgraded the `traffic_light` crate. - -## Re-exports with `pub use` - -Finally, you can combine the `pub` keyword with `use` to 're-export' something: - -```rust -mod a { - mod namespace { - pub fn function() {} - } -} - -pub use a::namespace::function; -``` - -Here, the `a` and `namespace` modules are not public, so users of our library -couldn't call `a::namespace` themselves. However, since we've `pub use`'d -`function`, it will be public. Users can just call `function` themselves, -directly. This allows us to organize our code internally however we'd like, -while presenting a different external interface. diff --git a/src/chYY-YY-public-api.md b/src/chYY-YY-public-api.md new file mode 100644 index 000000000..4b7228b58 --- /dev/null +++ b/src/chYY-YY-public-api.md @@ -0,0 +1,30 @@ +## Organizing your Public API + +Here, we will describe the properties that a good public API in Rust has in +order to be pleasant for others to use. + +### Re-exports with `pub use` + +If your internal code organization doesn't match your desired public API +organization, you can re-export items in the way you want them to be organized. + +To re-export a name, combine the `pub` keyword with `use`: + +```rust +# fn main() {} # this doesn't work if it's inside main +mod a { + pub mod namespace { + pub fn function() {} + } +} + +pub use a::namespace::function; +``` + +Here, the `a` module is not public to users of our library, so neither are its +children, even though `namespace` and `function` are public *within* our +library. So users of our library couldn't call `a::namespace::function()` +themselves. However, since we've re-exported `function()` with `pub use`, +`function()` will be public. Users can just call `function()` themselves, +directly. This allows us to organize our code internally however we'd like, +while presenting a different external interface.