English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Rust Object-Oriented

Object-oriented programming languages typically implement data encapsulation and inheritance and can invoke methods based on data.

Rust is not an object-oriented programming language, but these functionalities can still be achieved.

Encapsulation

Encapsulation is the strategy of displaying externally, which can be realized through the module mechanism in Rust, and each Rust file can be regarded as a module. The elements within a module can be explicitly indicated to the outside world through the pub keyword. This is detailed in the "Organization and Management" section.

"Class" is a commonly used concept in object-oriented programming languages. The 'class' encapsulates data, which is an abstraction of the same type of data entity and its handling methods. In Rust, we can use structures or enums to implement class functionality:

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, let's 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 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 (Polymorphism) concept, where polymorphism refers to the ability of a programming language to handle multiple types of data. In Rust, polymorphism is achieved through traits. Details about traits are provided in the "Traits" section. However, traits cannot implement attribute inheritance; they can only implement functions similar to "interfaces", so if you want to inherit a class's methods, it is best to define an example of the "parent class" in the "subclass".

In summary, Rust does not provide syntax sugar for inheritance and does not have an official inheritance method (equivalent to class inheritance in Java), but the flexible syntax can still achieve related functions.