Easy Tutorial
❮ Rust Loop Rust Comments ❯

Rust and Object-Oriented Programming

Object-oriented programming languages typically implement data encapsulation and inheritance, and allow methods to be called based on data.

Rust is not an object-oriented programming language, but it implements these features.

Encapsulation

Encapsulation is the strategy for external visibility. In Rust, encapsulation at the outermost level can be achieved through the module mechanism, and each Rust file can be considered a module. Elements within a module can be explicitly exposed to the outside using the pub keyword. This is detailed in the "Organization Management" chapter.

"Class" is often a common concept in object-oriented programming languages. A "class" encapsulates data, abstracting the same type of data entities and their processing methods. In Rust, we can use structs or enums to achieve the functionality of a class:

Example

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) {
        // Method body
    }
}

Below is a complete class example:

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:

from public method
from private method

Inheritance

Almost all other object-oriented programming languages can implement "inheritance," often described with the term "extend."

Inheritance is the implementation of the polymorphism concept, where polymorphism refers to a programming language's ability to handle code for 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 function like "interfaces." Therefore, to inherit methods from a class, it is best to define an instance of the "parent class" in the "child class."

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

❮ Rust Loop Rust Comments ❯