Sub topic 12
Privacy and encapsulation
This chapter assumes you know how to define structs, write impl blocks, and use &self and &mut self methods. Here you will see how Rust decides who can touch a struct's fields, and how to use that to protect your data.
Privacy is per module
In Rust, every item is private by default. A private item is visible only inside the module where it is defined, and inside that module's children. The pub keyword makes an item visible outside.
For structs, visibility is set separately for the struct and for each field. Marking a struct pub does not make its fields pub.
mod account {
pub struct Account {
owner: String,
balance: u64,
}
impl Account {
pub fn new(owner: &str) -> Self {
Self {
owner: owner.to_string(),
balance: 0,
}
}
pub fn deposit(&mut self, amount: u64) {
self.balance += amount;
}
pub fn balance(&self) -> u64 {
self.balance
}
pub fn owner(&self) -> &str {
&self.owner
}
}
}
use account::Account;
fn main() {
let mut acct = Account::new("Ada");
acct.deposit(50);
println!("{} has {}", acct.owner(), acct.balance());
}The fields owner and balance are private. Code in main cannot read or write them directly. It can only call the public methods.
Why hide fields
Hidden fields let the struct enforce its own rules. Here, balance can only grow through deposit. If you later add an overflow check or a transaction log, you change one method. Callers do not break.
The getters balance and owner give read-only access. A caller can see the value but cannot change it. Note that owner returns &str, a borrow, so the caller does not get ownership of the String.
What the compiler says
If main tries acct.balance = 1_000_000;, compilation fails:
error[E0616]: field `balance` of struct `Account` is privateWithout the new constructor, outside code also could not build an Account with struct literal syntax, because that syntax names every field. A struct with any private field can only be created outside its module through a public associated function.
Choosing visibility
| Marker | Visible to |
|---|---|
| (none) | The current module and its children |
| `pub` | Everyone who can reach the item |
| `pub(crate)` | Anywhere inside the same crate |
| `pub(super)` | The parent module |
Start private and widen only when needed. Making a field pub later is easy. Making a public field private again breaks every caller that used it.
Common mistakes
- Making all fields
pubout of habit. This removes any chance of enforcing invariants later. - Writing a setter for every field. A setter that accepts any value gives the same power as a public field. Prefer methods named for actions, such as
deposit. - Forgetting that privacy works at module level, not struct level. Other code in the same module can still touch private fields.
Exercise
A struct Temperature has a private field celsius: f64 and must never hold a value below -273.15. Which kind of function should be the only way to create it from outside the module, and what should it do?
Show answer
A public associated function such as new(celsius: f64) -> Option<Self> (or Result<Self, _>). It checks the value, returns None or an error when it is below -273.15, and otherwise builds the struct. Because the field is private, outside code cannot bypass the check.