Visibility
Visibility decides which code is allowed to name an item. In Rust everything is private to its own module by default, and pub and its variants widen that reach one step at a time.
Detailed Explanation
The plain-English rule: if you do not write pub, only the module that defines an item and that module's descendants can use it.
Note the two halves of that rule. The first half is the default, and it is the opposite of C++ and Java, where a top-level declaration in a header or a public class is reachable by anyone who includes or imports it. Rust flips the default because the safe direction is inward. Forgetting pub produces a compile error you fix in seconds. Forgetting private produces an accidental part of your public API that you cannot remove without a breaking release.
The second half is the exception people miss: privacy is per-module, not per-type. A child module can see everything in its ancestors, including private items. Two functions in the same module can touch each other's private struct fields. This is deliberate: the module, not the type, is the encapsulation boundary. It is why #[cfg(test)] mod tests can test private functions, and why splitting a type and its helpers into one module gives them shared access without making anything public.
The visibility modifiers, from narrowest to widest:
| Modifier | Visible to |
|---|---|
| (none) | The defining module and its descendants |
pub(super) | Additionally the parent module and its descendants |
pub(in crate::a::b) | Additionally the named ancestor module and its descendants |
pub(crate) | Everything in this crate, nothing outside it |
pub | Everything, including other crates — if the path to it is also public |
That last clause matters more than the table suggests. Visibility is checked along the whole path. A pub struct inside a private module is unreachable from outside, because callers cannot name the module. This is not a bug; it is the mechanism behind the re-export pattern, where you keep implementation modules private and pub use selected types at the crate root so that consumers write my_crate::Client instead of my_crate::internals::client::Client.
pub(crate) is the modifier you will use most in application code. It says "other parts of this program may use this, no external consumer may". Because it stops at the crate boundary, a pub(crate) item is never part of your semantic version contract, so you can rename or delete it freely.
Struct fields have their own visibility, independent of the struct. A pub struct with private fields is the standard way to enforce an invariant: outsiders construct it through a constructor that validates, and read it through methods. Making a field pub is a promise you may later regret, because it permits arbitrary mutation and locks in the field name and type. Enum variants are the exception: a pub enum exposes all of its variants and their fields, with no way to hide some.
The cost of getting visibility right is a little friction while you are exploring, and the discipline of deciding what the API actually is. The cost of getting it wrong is an API surface you are stuck supporting.
Code Examples
mod store {
// Public type, but the fields are private, so the invariant below holds.
pub struct Account {
id: u32,
balance_cents: i64, // no outsider can set this to a bad value
}
impl Account {
pub fn open(id: u32) -> Self {
Account { id, balance_cents: 0 }
}
pub fn balance_cents(&self) -> i64 {
self.balance_cents // read-only accessor
}
// Visible anywhere in this crate, never to a consumer of the library.
pub(crate) fn force_balance(&mut self, cents: i64) {
self.balance_cents = cents;
}
// No modifier: usable only inside `store` and its children.
fn audit_key(&self) -> String {
format!("acct-{}", self.id)
}
}
mod audit {
// A child module sees the parent's private items, including `audit_key`.
pub(super) fn log(account: &super::Account) {
println!("{}", account.audit_key());
}
}
pub fn open_and_log(id: u32) -> Account {
let account = Account::open(id);
audit::log(&account); // prints: acct-7 when called with 7
account
}
}
fn main() {
let mut account = store::open_and_log(7);
println!("{}", account.balance_cents()); // prints: 0
account.force_balance(500); // allowed: same crate
// account.balance_cents = 500; // error[E0616]: field is private
}The re-export pattern: private implementation modules, a curated public surface.
// The re-export pattern: private implementation modules, a curated public surface.
mod client; // src/client.rs, private
mod protocol; // src/protocol.rs, private
// Consumers write `my_crate::Client`, not `my_crate::client::Client`.
pub use client::Client;
pub use protocol::Error;Common Gotchas
`pub` inside a private module still does not escape
`mod internals { pub struct Handle; }` cannot be reached from outside the crate, because the path `internals` is private. The fix is `pub use internals::Handle;` at a public level, not more `pub` on the struct.
A public field is a permanent promise
once a field is `pub`, callers may read and mutate it, and renaming or retyping it is a breaking change. Start fields private and add accessors; widening later is easy, narrowing is not.
`pub` enum variants cannot be hidden individually
if an enum is public, every variant and every variant field is public. Adding a variant is a breaking change for callers who match exhaustively, which is why library authors often mark such enums `#[non_exhaustive]`.
Privacy is a compile-time check, not a security boundary
it stops accidental coupling. It does not protect data at runtime, and `unsafe` code or transmutation can still read private bytes.