OOP in Rust
While there is no unique definition of what object-orientation in a programming language is, it is clear by now that in Rust you can express several important OO-concepts.
- Objects with data (their state) and methods (their behavior):
- Rust has these--structs (and other types such as enums) have data and
impl
blocks provide methods on them. The definitions of structure and behavior are separate.
- Rust has these--structs (and other types such as enums) have data and
- Encapsulation of data and implementation:
- In other words--external code can only change or interact with an object through its public methods. In Rust by default everything is private, so not accessible from the outside. You can decide which types, functions, methods and modules are public by adding a
pub
keyword before their definition. For more detail, see Chapter 8, Organizing Code and Macros in the section, Visibility of items.
- In other words--external code can only change or interact with an object through its public methods. In Rust by default everything is private, so not accessible from the outside. You can decide which types, functions, methods and modules are public by adding a
- Inheritance to promote code reuse and use polymorphism:
- In Rust, inheritance, strictly speaking, does not exist: a struct cannot inherit its fields or methods from...