Rust Object Orientation
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 features are all achievable.
Encapsulation
Encapsulation is the strategy of what to expose externally; in Rust, the outermost encapsulation can be achieved through the module mechanism, and every Rust file can be seen as a module, with elements inside a module exposed via the pub keyword. This is described in detail in the "Organization and Management" chapter.
"Class" is a concept commonly used in object-oriented programming languages. A "class" encapsulates data and is an abstraction of a class of data entities and their processing methods. In Rust, we can use structs or enums to implement the functionality of classes:
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
)
{
}
}
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 idea of polymorphism (Polymorphism), which refers to code where a programming language can handle multiple types of data. In Rust, polymorphism is achieved through traits. Details about traits are given in the "Traits" chapter. However, traits cannot implement inheritance of properties; they can only implement something like an "interface", so to inherit a class's methods it's best to define an instance of the "parent class" in the "child class".
In summary, Rust does not provide syntax sugar related to inheritance, nor an official means of inheritance (fully equivalent to class inheritance in Java), but its flexible syntax can still achieve related functionality.