Skip to content

Commit 94c10a3

Browse files
authored
Merge pull request rust-lang#12 from cramertj/pub-restricted
Add pub(restricted) docs
2 parents 4076f44 + 2c1c42f commit 94c10a3

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

Diff for: src/visibility-and-privacy.md

+61
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,67 @@ For a Rust program to pass the privacy checking pass, all paths must be valid
134134
accesses given the two rules above. This includes all use statements,
135135
expressions, types, etc.
136136

137+
## `pub(in path)`, `pub(crate)`, `pub(super)`, and `pub(self)`
138+
139+
In addition to public and private, Rust allows users to declare an item as
140+
visible within a given scope. The rules for `pub` restrictions are as follows:
141+
- `pub(in path)` makes an item visible within the provided `path`. `path` must
142+
be a parent module of the item whose visibility is being declared.
143+
- `pub(crate)` makes an item visible within the current crate.
144+
- `pub(super)` makes an item visible to the parent module. This equivalent to
145+
`pub(in super)`.
146+
- `pub(self)` makes an item visible to the current module. This is equivalent
147+
to `pub(in self)`.
148+
149+
Here's an example:
150+
151+
```rust
152+
pub mod outer_mod {
153+
pub mod inner_mod {
154+
// This function is visible within `outer_mod`
155+
pub(in outer_mod) fn outer_mod_visible_fn() {}
156+
157+
// This function is visible to the entire crate
158+
pub(crate) fn crate_visible_fn() {}
159+
160+
// This function is visible within `outer_mod`
161+
pub(super) fn super_mod_visible_fn() {
162+
// This function is visible since we're in the same `mod`
163+
inner_mod_visible_fn();
164+
}
165+
166+
// This function is visible
167+
pub(self) fn inner_mod_visible_fn() {}
168+
}
169+
pub fn foo() {
170+
inner_mod::outer_mod_visible_fn();
171+
inner_mod::crate_visible_fn();
172+
inner_mod::super_mod_visible_fn();
173+
174+
// This function is no longer visible since we're outside of `inner_mod`
175+
// Error! `inner_mod_visible_fn` is private
176+
//inner_mod::inner_mod_visible_fn();
177+
}
178+
}
179+
180+
fn bar() {
181+
// This function is still visible since we're in the same crate
182+
outer_mod::inner_mod::crate_visible_fn();
183+
184+
// This function is no longer visible since we're outside of `outer_mod`
185+
// Error! `super_mod_visible_fn` is private
186+
//outer_mod::inner_mod::super_mod_visible_fn();
187+
188+
// This function is no longer visible since we're outside of `outer_mod`
189+
// Error! `outer_mod_visible_fn` is private
190+
//outer_mod::inner_mod::outer_mod_visible_fn();
191+
192+
outer_mod::foo();
193+
}
194+
195+
fn main() { bar() }
196+
```
197+
137198
## Re-exporting and Visibility
138199

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

0 commit comments

Comments
 (0)