Rust 編程視頻教程(進階)——021

視頻地址

頭條地址:https://www.ixigua.com/i6775861706447913485

源碼地址

github地址:見擴展鏈接。

講解內容

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>, //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>,/<string>

}

impl Draw for SelectBox {

fn draw(&self) {

println!("draw selectBox, width = {}, height = {}, options = {:?}",

self.width, self.height, self.options);

}

}

////複習

//pub struct Screen {

// pub components: Vec,

//}

//

//impl Screen

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

}

```


分享到:


相關文章: