Skip to content

Commit

Permalink
Merge pull request #12 from cramertj/pub-restricted
Browse files Browse the repository at this point in the history
Add pub(restricted) docs
  • Loading branch information
steveklabnik authored Mar 27, 2017
2 parents 4076f44 + 2c1c42f commit 94c10a3
Showing 1 changed file with 61 additions and 0 deletions.
61 changes: 61 additions & 0 deletions src/visibility-and-privacy.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,67 @@ For a Rust program to pass the privacy checking pass, all paths must be valid
accesses given the two rules above. This includes all use statements,
expressions, types, etc.

## `pub(in path)`, `pub(crate)`, `pub(super)`, and `pub(self)`

In addition to public and private, Rust allows users to declare an item as
visible within a given scope. The rules for `pub` restrictions are as follows:
- `pub(in path)` makes an item visible within the provided `path`. `path` must
be a parent module of the item whose visibility is being declared.
- `pub(crate)` makes an item visible within the current crate.
- `pub(super)` makes an item visible to the parent module. This equivalent to
`pub(in super)`.
- `pub(self)` makes an item visible to the current module. This is equivalent
to `pub(in self)`.

Here's an example:

```rust
pub mod outer_mod {
pub mod inner_mod {
// This function is visible within `outer_mod`
pub(in outer_mod) fn outer_mod_visible_fn() {}

// This function is visible to the entire crate
pub(crate) fn crate_visible_fn() {}

// This function is visible within `outer_mod`
pub(super) fn super_mod_visible_fn() {
// This function is visible since we're in the same `mod`
inner_mod_visible_fn();
}

// This function is visible
pub(self) fn inner_mod_visible_fn() {}
}
pub fn foo() {
inner_mod::outer_mod_visible_fn();
inner_mod::crate_visible_fn();
inner_mod::super_mod_visible_fn();

// This function is no longer visible since we're outside of `inner_mod`
// Error! `inner_mod_visible_fn` is private
//inner_mod::inner_mod_visible_fn();
}
}

fn bar() {
// This function is still visible since we're in the same crate
outer_mod::inner_mod::crate_visible_fn();

// This function is no longer visible since we're outside of `outer_mod`
// Error! `super_mod_visible_fn` is private
//outer_mod::inner_mod::super_mod_visible_fn();

// This function is no longer visible since we're outside of `outer_mod`
// Error! `outer_mod_visible_fn` is private
//outer_mod::inner_mod::outer_mod_visible_fn();

outer_mod::foo();
}

fn main() { bar() }
```

## Re-exporting and Visibility

Rust allows publicly re-exporting items through a `pub use` directive. Because
Expand Down

0 comments on commit 94c10a3

Please sign in to comment.