Rust items are private by default. Adding `pub` exposes an item; on a struct field, it permits direct access and modification. Public fields generally suit data-only containers. Otherwise, keep fields private and expose access through methods. section 4.4
When shaping a public API:
- Expose the struct and methods needed by external callers. Types returned by public methods must also be public. section 6.11.1
- Keep fields private when access should be controlled, and provide public accessors, mutators, or setters as needed. section 4.4
Listing 4.8 A pizza with pub toppings
#[derive(Debug, Clone)]
pub struct Pizza {
pub toppings: Vec<String>, #1
}
A public `toppings` field allows callers to modify a pizza's data directly. section 4.4
Listing 4.9 Providing access to our pizza toppings
impl Pizza {
pub fn toppings(&self) -> &[String] { #1
self.toppings.as_ref()
}
pub fn toppings_mut(&mut self) -> &mut Vec<String> { #2
&mut self.toppings
}
pub fn set_toppings(&mut self, toppings: Vec<String>) { #3
self.toppings = toppings;
}
}
Public methods provide an alternative interface for reading and changing private toppings. section 4.4







