Rust Object-Oriented

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 all of these features are implemented.

Encapsulation

Encapsulation is a strategy for external exposure. In Rust, the outermost encapsulation can be implemented through the module mechanism, and every Rust file can be viewed as a module. Elements within a module can be made visible externally using the `pub` keyword. This was detailed in the "Organization Management" chapter.

"Class" is a concept commonly used in object-oriented programming languages. A "class" encapsulates data, serving as an abstraction of the same type of data entities and their processing methods. In Rust, we can use structs or enums to implement class functionality:

Example

pub struct ClassName {
    pub field: Type,
}

pub impl ClassName {
    fn some_method(&self) {
        // Method function body
    }
}

pub enum EnumName {
    A,
    B,
}

pub impl EnumName {
    fn some_method(&self) {

    }
}

Below we build a complete class:

Example

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 result:

from public method
from private method

Inheritance

Almost all other object-oriented programming languages can implement "inheritance" and use the word "extend" to describe this action.

Inheritance is the implementation of the polymorphism concept. Polymorphism refers to code in a programming language that can handle multiple types of data. In Rust, polymorphism is implemented through traits. Details about traits have been provided in the "Traits" chapter. However, traits cannot implement property inheritance; they can only implement functionality similar to "interfaces." Therefore, if you want to inherit the methods of a class, it is best to define an instance of the "parent class" within the "subclass."

In summary, Rust does not provide syntax sugar related to inheritance, nor does it have an official inheritance mechanism (fully equivalent to class inheritance in Java), but its flexible syntax can still implement related functionality.

Other Extensions