20.7 Modules and Encapsulation

Encapsulation in OOP means bundling data with methods while restricting direct access to that data. Rust achieves this through:

  • Modules and Visibility: By default, items are private within a module. Mark them pub to expose them externally.
  • Private Struct Fields: A struct’s fields can remain private, with only certain methods exposed, preventing outside code from directly modifying internal data.
  • Traits: By implementing traits privately within a module, you can hide the implementation details and only present a public interface.

20.7.1 Short Example: Struct and Methods Hiding Implementation Details

mod library {
    // This struct is visible outside the module, but its fields are not.
    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
        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
}

In this example, we encapsulate the internal details of Counter (like current and step) by making them private fields, while exposing only certain methods (new, next) to the outside world. This is analogous to encapsulation in OOP.