Rust - Basic - 16 - Object Oriented Programming

オブジェクト指プログラミング

OOP

理解

  • 多態性の特徴(すべてではありません)

    抽象: オブジェクトはデータと振る舞いを含む 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();
            }
        }
    }
    

参照元

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