20.7 Modules and Encapsulation
Encapsulation in OOP often means bundling data and methods together while restricting direct access. Rust handles this primarily through:
- Modules and Visibility: By default, items in a module are private. Marking them
pub
exposes them outside the module. - Private Fields: Struct fields can remain private, offering only certain public methods to manipulate them.
- Traits: Implementation details can be hidden; the public interface is whatever the trait defines.
20.7.1 Short Example: Struct and Methods Hiding Implementation Details
mod library { // This struct is publicly visible, but its fields are private to the module. pub struct Counter { current: i32, step: i32, } impl Counter { // Public constructor method pub fn new(step: i32) -> Self { Self { current: 0, step } } // Public method to advance the counter pub fn next(&mut self) -> i32 { self.current += self.step; self.current } // Private helper function, not visible outside the module fn reset(&mut self) { self.current = 0; } } } fn main() { let mut counter = library::Counter::new(2); println!("Next count: {}", counter.next()); // counter.reset(); // Error: `reset` is private and thus inaccessible }
Here, the internal fields current
and step
remain private. Only the new
and next
methods are exposed.