Move pub use discussion to the library chapter

Maybe we should think about a separate book about creating a library ;)
This commit is contained in:
Carol (Nichols || Goulding)
2016-08-26 17:41:35 -07:00
parent 4bab40d45e
commit 56f69991cf
3 changed files with 31 additions and 20 deletions
+1
View File
@@ -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)
-20
View File
@@ -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.
+30
View File
@@ -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.