Visibility and encapsulation
Rust encapsulates by module visibility, not by class boundaries. Fields and items are private to their module unless marked pub. Privacy is how you keep a struct's invariants from being broken by outsiders.
Detailed Explanation
In Java, private means "this class" and protected means "this class and its subclasses". In Rust there are no subclasses, and the privacy boundary is the module. An item without pub is visible in its parent module and the parent's descendants, not in sibling modules and not in other crates. pub makes it visible wherever the parent is visible. pub(crate) and pub(super) narrow that.
This is the mechanism that replaces private fields on a class. Write
pub struct Session {
token: String,
user_id: u64,
}
and any other module can construct a Session with any token, including an empty one. Write the fields without pub and only the defining module can name them. Outsiders must go through Session::new and the methods you expose. That is how you enforce "a token is never empty" or "user_id is never zero": the constructor checks, the fields stay private, and there is no subclass that can reach in and write them.
Privacy also applies to structs, enums, traits, functions, and modules themselves. A common pattern is pub struct Session { ... } with private fields, plus pub fn token(&self) -> &str as a read-only getter. You do not generate getters for every field by habit. You expose the operations the rest of the program needs.
Why modules, not classes, are the boundary: a type and the functions that maintain it often want to sit in one file together, including helper structs that should see each other's fields. Java's "private to the class" forces those helpers into nested classes or package-private hacks. Rust's "private to the module" lets Session and SessionError and fn parse_token share fields without making those fields public to the crate.
The cost is that a file that grows into several modules will suddenly stop compiling when you split it, because field access that was legal inside one module is illegal across the new boundary. That is working as designed: the split made a new encapsulation edge. Either keep the types in one module, or add methods and pub(crate) where the new edge is real.
pub on an enum's variants makes those variants part of your API. If you later want to add a variant, every match outside your crate breaks. Keep enum variants private when the enum is an implementation detail, and expose constructors and methods instead.
When you reach for this: any time a struct has an invariant. When you do not: plain data-transfer structs that exist to be serialised can have public fields, because there is no invariant to protect.
Code Examples
mod session {
pub struct Session {
token: String, // private: only this module can read or write it
user_id: u64,
}
impl Session {
pub fn new(token: String, user_id: u64) -> Result<Self, &'static str> {
if token.is_empty() {
return Err("token must not be empty");
}
Ok(Self { token, user_id })
}
pub fn user_id(&self) -> u64 {
self.user_id
}
}
}
fn main() {
let s = session::Session::new("abc".into(), 17).unwrap();
println!("{}", s.user_id()); // prints: 17
// s.token would not compile here: the field is private to `session`
}Common Gotchas
`pub struct` does not publish the fields
the type can be named, but a struct literal still requires every field to be visible. Private fields force callers through your constructor.
Privacy is the module, not the file
two types in the same file but different `mod` blocks cannot see each other's private fields. Two types in the same module, even across files via `mod foo;`, can.
`pub` enum variants are a compatibility promise
adding a variant later breaks downstream `match`es unless they use `..` or you marked the enum `#[non_exhaustive]`.
`pub(crate)` is the usual internal default
it lets the rest of your crate use the item without making it part of the published API.