Rust object oriented


Release date:2023-11-10 Update date:2023-11-10 Editor:admin View counts:185

Label:

Rust object oriented

Object-oriented programming languages usually implement data encapsulation and inheritance and can call methods based on data.

Rust is not an object-oriented programming language, but these functions areimplemented.

Encapsulation

Encapsulation is the strategy of external display. In Rust, the outermost encapsulation can be achieved through the mechanism of the module, and each Rust file can be regarded as a module, and the elements in the module can beexplicitly indicated by the pub keyword. This is described in detail in thechapter “Organization and Management”.

“class” is often a common concept in object-oriented programming languages. “class” encapsulates data and abstracts the same kind of data entity and its processing methods. In Rust, we can use structures or enumerated classes to implement the functions of classes:

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) {
    }
}

Build a complete class below:

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

Inherit

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

Inheritance is the implementation of the idea of Polymorphism, which refers to code that a programming language can handle many types of data. In Rust, polymorphism is implemented through trait. Details of the features are givenin the “Features” section. However, the property cannot inherit the property, and can only implement the function similar to the “interface”, so the method that wants to inherit a class had better define the instance of the “parent class” in the “subclass”.

To sum up, Rust does not provide syntactic sugar related to inheritance, nordoes it have an official means of inheritance (completely equivalent to inheritance of classes in Java), but flexible syntax can still achieve related functions.

Powered by TorCMS (https://github.com/bukun/TorCMS).