Rust 程式設計視訊教程(進階)——021_1 trait 物件的例子

linghuyichong發表於2020-02-11

頭條地址:https://www.ixigua.com/i677586170644791348...
B站地址:https://www.bilibili.com/video/av81202308/

github地址:https://github.com/anonymousGiga/learn_rus...

trait物件的例子:
(1) mkdir learn_oo2
(2)cd learn_oo2,編輯Cargo.toml

[workspace]
members = [
        "gui",
        "main",
]

(3) cargo new gui –lib
(4) 編輯gui/src/lib.rs原始碼

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

pub struct Screen {
    pub components: Vec<Box<dyn Draw>>,  //trait物件,使用dyn關鍵字
}

impl Screen {
    pub fn run(&self) {
        for component in self.components.iter() {
            component.draw();
        }
    }
}

pub struct Button {
    pub width: u32,
    pub height: u32,
    pub label: String,
}

impl Draw for Button {
    fn draw(&self) {
        println!("draw button, width = {}, height = {}, label = {}",
                 self.width, self.height, self.label);
    }
}

pub struct SelectBox {
    pub width: u32,
    pub height: u32,
    pub options: Vec<String>,
}

impl Draw for SelectBox {
    fn draw(&self) {
        println!("draw selectBox, width = {}, height = {}, options = {:?}",
                 self.width, self.height, self.options);
    }
}

////複習
//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();
//        }
//    }
//}

(5) cargo new main
(6) 編輯Cargo.toml檔案,新增:

[dependencies]
gui = {path = "../gui"}

(7) 編輯src/main.rs原始碼

use gui::{Screen, Button, SelectBox};
fn main() {
    let screen = Screen {
        components: vec![
            Box::new(SelectBox {
                width: 75,
                height: 10,
                options: vec![
                    String::from("Yes"),
                    String::from("Maybe"),
                    String::from("No")
                ],
            }),
            Box::new(Button {
                width: 50,
                height: 10,
                label: String::from("OK"),
            }),
        ],
    };

    //let screen = Screen {
    //    components: vec![
    //        SelectBox {
    //            width: 75,
    //            height: 10,
    //            options: vec![
    //                String::from("Yes"),
    //                String::from("Maybe"),
    //                String::from("No")
    //            ],
    //        },
    //        //Button {
    //        //    width: 50,
    //        //    height: 10,
    //        //    label: String::from("OK"),
    //        //},
    //    ]
    //};
    screen.run();
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

令狐一衝

相關文章