Skip to content

Commit adf1673

Browse files
committed
Add pub(restricted) docs
1 parent 4076f44 commit adf1673

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

src/visibility-and-privacy.md

+35
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,41 @@ 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(crate)` and `pub(in path)`
138+
139+
In addition to public and private, Rust allows users to declare an item as
140+
`pub(crate)` or `pub(in path)`. These restrictions make it possible to specify
141+
the exact scope of an item's visibility. As their names would suggest,
142+
`pub(crate)` makes an item public within the current crate, and `pub(in path)`
143+
makes an item public within the specified path.
144+
145+
Here's an example using `pub(crate)` and `pub(in path)`:
146+
147+
```rust
148+
pub mod outer_mod {
149+
pub mod inner_mod {
150+
// This function is public to the entire crate
151+
pub(crate) fn crate_visible_fn() {}
152+
153+
// This function is public within `outer_mod`
154+
pub(in outer_mod) fn outer_mod_visible_fn() {}
155+
}
156+
fn foo() {
157+
inner_mod::crate_visible_fn();
158+
inner_mod::outer_mod_visible_fn();
159+
}
160+
}
161+
162+
fn bar() {
163+
// This function is still visible since we're in the same crate
164+
outer_mod::inner_mod::crate_visible_fn();
165+
166+
// This function is no longer visible since we're outside of `outer_mod`
167+
// Error! `outer_mod_visible_fn` is private
168+
//outer_mod::inner_mod::outer_mod_visible_fn();
169+
}
170+
```
171+
137172
## Re-exporting and Visibility
138173

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

0 commit comments

Comments
 (0)