Characteristics of OOP

Object Oriented Programming

Objects Contain Data and Behavior

Object-oriented programs are made up of objects. An object packages both data and the procedures that operate on that data. The procedures are typically called method or operations.

In Rust, structs and enums have data, and impl blocks provide methods on structs and enums.

Encapsulation that Hides Implementation Details

Another aspect, encapsulation, is that the implementation details of an object aren’t accessible to code using that object. The only way to interact with an object is through its public API.

In Rust, the pub keyword can be used to decide which modules, types, functions and methods in code should be public(and by default everything else is private).

Inheritance as a Type System and as Code Sharing

Inheritance is a mechanism whereby an object can inherit elements from another object’s definition, thus gaining the parent object’s data and behavior without defining them again.

Rust does not support inheritance, at least there is not way to define a struct that inherits the parent struct’s field and method implementations without using a macro.

Polymorphism

Polymorphism refers to that one can substitute multiple objects for each other at runtime if they share certain characteristics. Compare to inheritance, it’s a more general concept that refers to code that can work with data of multiple types.

Rust instead uses generics to abstract over different possible types and trait bounds to impose constraints on what those types must provide. This is called bounded parametric polymorphism.

Using Trait Objects That Allow for Values of Different Types

Defining a Trait for Common Behavior

Trait objects can be used in place of a generic or concrete type. Rust’s type system will ensure at compile time that any value used in that context will implement the trait object’s trait.

Traits object are associated with methods in sense that they combine data and behavior, however, datas can’t be added to a trait object.

pub trait Draw {
    fn draw(&self);
}

To use the trait