Rust - Basic - 16 - Object Oriented Programming

Object Oriented Programming

OOP

Comprehension

  • Some (but not all) polymorphic features

    Abstraction: objects contain data and behavior

    Encapsulation: hiding implementation details

    Inheritance: as a type system and a way to share code

  • trait object

    Box<dyn traitA> is a trait object resolved at runtime, with some performance cost—avoid it when possible

    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