Sub topic 12
Privacy and encapsulation
This chapter assumes you can define structs and write impl blocks with associated functions and the three self receivers. It also assumes you know what a module is. It covers how Rust decides who may touch a struct's fields, and how to use that to keep a struct's state valid.
Privacy is decided by modules
In Rust, everything is private by default. A private item is visible inside the module where it is defined and in that module's descendants. Code outside that module cannot name it.
Privacy is checked per module, not per type. Two functions in the same module can both read each other's private fields. A child module, such as a tests module, can also see the private items of its parent. A parent cannot see the private items of its children.
The pub keyword widens visibility. For structs, you apply it separately to the struct and to each field:
pub struct Accountlets other modules name the type.pub balance: u64lets other modules read and write that field.- A field without
pubstays private even if the struct is public.
Hiding fields behind a constructor
When a struct has any private field, code outside its module cannot build it with a struct literal. The compiler reports error E0451 for this. Code outside the module also cannot read the field directly, which gives error E0616. The same rule blocks struct update syntax (..other) outside the module, because that syntax touches every remaining field.
So the module must offer a public associated function. That function is the only way in, and it can check its input:
mod temperature {
#[derive(Debug)]
pub struct Celsius {
degrees: f64,
}
impl Celsius {
pub const MIN: f64 = -273.15;
pub fn new(degrees: f64) -> Result<Self, String> {
if degrees.is_nan() || degrees < Self::MIN {
Err(format!("{degrees} is below absolute zero"))
} else {
Ok(Self { degrees })
}
}
pub fn degrees(&self) -> f64 {
self.degrees
}
pub fn set_degrees(&mut self, degrees: f64) -> Result<(), String> {
*self = Self::new(degrees)?;
Ok(())
}
}
}
use temperature::Celsius;
fn main() {
let mut t = Celsius::new(20.0).unwrap();
println!("{}", t.degrees());
match t.set_degrees(-300.0) {
Ok(()) => println!("changed"),
Err(e) => println!("rejected: {e}"),
}
println!("{:?}", t);
}An invariant is a condition that must always hold for a value to be valid. Here it is "degrees is a number at or above absolute zero". Because the field is private and every path that writes it goes through new, no Celsius can exist that breaks the invariant. The reader of main does not need to check for bad values.
If degrees were pub, any caller could write t.degrees = -500.0 and the guarantee would be gone.
Choosing what to expose
Each public method becomes part of the type's contract. Changing it later can break callers. Private fields can be renamed, retyped, or replaced freely.
Some conventions:
- Name a getter after the field, without a
get_prefix:balance(), notget_balance(). - Return
Copyvalues such as integers by value. - Return
&strrather than&String, and&[T]rather than&Vec<T>. This exposes less of the internal representation. - Add a setter only when callers need to change the value. If you add one, validate in it.
- Avoid returning
&mutto an internal field that has an invariant. The caller could then break the invariant through that reference.
Finer-grained visibility
Plain pub means "visible everywhere the parent is visible". Restricted forms limit the audience:
| Modifier | Visible to |
|---|---|
| (none) | The current module and its descendants |
| `pub(self)` | Same as no modifier |
| `pub(super)` | The parent module and its descendants |
| `pub(crate)` | The whole crate, but not other crates |
| `pub(in path)` | The named ancestor module and its descendants |
| `pub` | Anywhere the item itself can be reached |
The next example uses three levels on one struct:
mod shop {
pub mod inventory {
pub struct Item {
pub name: String,
pub(crate) sku: u32,
pub(super) cost_cents: u64,
quantity: u32,
}
impl Item {
pub fn new(name: &str, sku: u32, cost_cents: u64, quantity: u32) -> Self {
Self {
name: name.to_string(),
sku,
cost_cents,
quantity,
}
}
pub fn quantity(&self) -> u32 {
self.quantity
}
}
}
pub fn total_cost(item: &inventory::Item) -> u64 {
item.cost_cents * item.quantity() as u64
}
}
fn main() {
let item = shop::inventory::Item::new("pen", 7, 120, 10);
println!("{} {} {}", item.name, item.sku, shop::total_cost(&item));
}total_cost lives in shop, the parent of inventory, so it can read the pub(super) field cost_cents. It cannot read quantity, so it calls the getter. main is in the crate root, so it can read sku (pub(crate)) but not cost_cents.
The diagram shows how the compiler decides whether an access to a field is allowed.
Tuple structs and enums
Tuple struct fields follow the same rule. In pub struct Meters(f64); the f64 is private, so outside the module the type cannot be constructed with Meters(1.0) or read with .0. Write pub struct Meters(pub f64); to make the field public. This matters for the newtype pattern later in the series.
Enum variants differ. Variants and their fields are always as public as the enum itself, and you cannot make a single variant private.
Edge cases
- Sibling code shares access. If two types are defined in the same module, each can read the other's private fields. If you want a hard boundary between them, put them in separate modules.
- Tests see private items. A
#[cfg(test)] mod testsplaced inside the module can call private functions and read private fields throughuse super::*;. - Public API across crates. For a library, a public struct with private fields can gain new fields in a later release without breaking callers. A struct with all public fields cannot. The
#[non_exhaustive]attribute gives a public-field struct the same freedom, but outside the defining crate it also blocks struct literals. - Privacy is not security. It is a compile-time check that protects invariants from honest mistakes. It does not stop
unsafecode or code in the same crate from working around your design.
Exercise
In main, outside the account module, you write Account { owner: String::from("Ada"), balance: 1_000 }, where Account has private owner and balance fields and a public new(owner: &str) constructor. Why does it fail, and what is the smallest change that lets main create an account with a starting balance of 1000 while still keeping balance private?
Show answer
It fails with E0451 because the fields are private, and code outside account cannot use a struct literal for a struct with private fields. Keep the fields private and add a public constructor such as pub fn with_balance(owner: &str, balance: u64) -> Self inside the impl block. Alternatively, call new and then deposit(1000). In both cases the module still controls how balance is set, so it can add validation later.
Exercise
A struct Inventory has a private items: Vec<String> field and promises at most 5 items. You add pub fn items_mut(&mut self) -> &mut Vec<String> for convenience. What breaks, and what would you write instead?
Show answer
The method gives callers a mutable reference to the whole Vec, so they can push past 5 items, and the invariant is lost. Remove items_mut. Add pub fn add(&mut self, item: String) -> Result<(), String> that returns an error when the length is already 5, and pub fn items(&self) -> &[String] for read-only access.