7.21. Rust object oriented

发布时间 : 2025-10-25 13:33:20 UTC      

Page Views: 9 views

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.

7.21.1. 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 

7.21.2. 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.

《地理信息系统原理、技术与方法》  97

最近几年来,地理信息系统无论是在理论上还是应用上都处在一个飞速发展的阶段。 GIS被应用于多个领域的建模和决策支持,如城市管理、区划、环境整治等等,地理信息成为信息时代重要的组成部分之一; “数字地球”概念的提出,更进一步推动了作为其技术支撑的GIS的发展。 与此同时,一些学者致力于相关的理论研究,如空间感知、空间数据误差、空间关系的形式化等等。 这恰好说明了地理信息系统作为应用技术和学科的两个方面,并且这两个方面构成了相互促进的发展过程。