Rust Object
# Rust Object-Oriented Programming
Object-oriented programming languages typically implement data encapsulation and inheritance, and can call methods based on data.
Rust is not an object-oriented programming language, but these features are all achievable.
### Encapsulation
Encapsulation is the strategy of presenting an external interface. In Rust, encapsulation at the outermost layer can be achieved through the module mechanism. Each Rust file can be considered a module, and elements within a module can be explicitly exposed to the outside using the `pub` keyword. This is detailed in the "Project Management" chapter.
"Classes" are a common concept in object-oriented programming languages. A "class" encapsulates data and is an abstraction of a data entity and its processing methods. In Rust, we can use structs or enums to achieve class-like functionality:
## Example
```rust
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){
}
}
Let's build a complete class:
## Example
second.rs
```rust
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
```rust
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 can implement "inheritance" and use the term "extend" to describe this action.
Inheritance is an implementation of the Polymorphism concept. Polymorphism refers to code that can handle multiple types of data. In Rust, polymorphism is achieved through traits. Details about traits are provided in the "Traits" chapter. However, traits cannot implement attribute inheritance; they can only implement functionality similar to "interfaces". Therefore, to inherit a class's methods, it is best to define an instance of the "parent class" within the "child class".
In summary, Rust does not provide syntactic sugar related to inheritance, nor does it have an official inheritance mechanism (completely equivalent to class inheritance in Java). However, its flexible syntax can still achieve related functionality.
YouTip