Object-Oriented Programming in Rust
Object-oriented programming languages typically implement data encapsulation and inheritance, and allow methods to be called based on data.
While Rust is not an object-oriented programming language, it can achieve these functionalities.
Encapsulation
Encapsulation is a strategy for controlling visibility. In Rust, the outermost level of encapsulation can be implemented through the module mechanism. Each Rust file can be considered a module, and elements within the module can be made public using the pub
keyword. This was covered in detail in the "Organization Management" chapter.
"Classes" are a common concept in object-oriented programming languages. A class encapsulates data and represents an abstraction of a specific type of data entity and its processing methods. In Rust, we can use structs or enums to implement class functionality:
pub struct ClassName {
pub field: Type,
}
pub impl ClassName {
fn some_method(&self) {
// Method body
}
}
pub enum EnumName {
A,
B,
}
pub impl EnumName {
fn some_method(&self) {
}
}
Here's how to build a complete class:
// second.rs
pub struct ClassName {
field: i32,
}
impl ClassName {
pub fn new(value: i32) -> ClassName {
ClassName {
field: value
}
}
pub fn public_method(&self) {
println!("from public method");
self.private_method();
}
fn private_method(&self) {
println!("from private method");
}
}
// main.rs
mod second;
use second::ClassName;
fn main() {
let object = ClassName::new(1024);
object.public_method();
}
Output:
from public method
from private method
Inheritance
Almost all other object-oriented programming languages implement "inheritance" and use the word "extend" to describe this action.
Inheritance is an implementation of polymorphism, which refers to code that can handle multiple types of data. In Rust, polymorphism is implemented through traits. The details about traits were covered in the "Traits" chapter. However, traits cannot implement property inheritance and can only implement functionality similar to "interfaces". Therefore, to inherit methods from a "parent class", it's best to define an instance of the "parent class" in the "child class".
In summary, Rust doesn't provide syntactic sugar for inheritance, nor does it have official inheritance mechanisms (completely equivalent to class inheritance in Java). However, its flexible syntax still allows you to achieve similar functionality.