Rust - Basic - 16 - Object Oriented Programming

Object Oriented Programming

OOP

Comprehension

  • 一些多态特征(不是全部)

    抽象:对象包含数据和行为 Objects Contain Data and Behavior

    封装:隐藏实现细节的封装 Encapsulation that Hides Implementation Details

    继承:继承作为类型系统和代码共享的方式 Inheritance as a Type System and as Code Sharing

  • trait object

    Box 是 trait object,Rust 需要在运行时解析,会消耗一定的性能 —— 尽量不要使用

    pub trait Draw {
        fn draw(&self);
    }
    // trait object
    pub struct Screen {
        pub components: Vec<Box<dyn Draw>>,
    }
    impl Screen {
        pub fn run(&self) {
            for component in self.components.iter() {
                component.draw();
            }
        }
    }
    // generic type + trait buond
    pub struct Screen<T: Draw> {
        pub components: Vec<T>,
    }
    impl<T> Screen<T>
    where
        T: Draw,
    {
        pub fn run(&self) {
            for component in self.components.iter() {
                component.draw();
            }
        }
    }
    

Origin

https://doc.rust-lang.org/book/ch17-00-oop.html