"首次提交"
This commit is contained in:
1
p16.fearless_conscurrency/shared_trait/.gitignore
vendored
Executable file
1
p16.fearless_conscurrency/shared_trait/.gitignore
vendored
Executable file
@ -0,0 +1 @@
|
||||
/target
|
8
p16.fearless_conscurrency/shared_trait/Cargo.toml
Executable file
8
p16.fearless_conscurrency/shared_trait/Cargo.toml
Executable file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "shared_trait"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
51
p16.fearless_conscurrency/shared_trait/src/lib.rs
Executable file
51
p16.fearless_conscurrency/shared_trait/src/lib.rs
Executable file
@ -0,0 +1,51 @@
|
||||
//定义一个Draw trait,所有实现了Draw trait的类型都要具有draw方法。
|
||||
pub trait Draw {
|
||||
fn draw(&self);
|
||||
}
|
||||
|
||||
pub struct Screen {
|
||||
pub components: Vec<Box<dyn Draw>>,
|
||||
}
|
||||
|
||||
impl Screen {
|
||||
pub fn new() -> Screen {
|
||||
Screen { components: vec![] }
|
||||
}
|
||||
pub fn add(&mut self, comp: Box<dyn Draw>) {
|
||||
self.components.push(comp)
|
||||
}
|
||||
pub fn run(&self) {
|
||||
if self.components.len() == 0 {
|
||||
println!("has no components!");
|
||||
return;
|
||||
}
|
||||
for obj in self.components.iter() {
|
||||
obj.draw();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Button {
|
||||
width: u32,
|
||||
height: u32,
|
||||
text: String,
|
||||
}
|
||||
|
||||
impl Button {
|
||||
pub fn new(width: u32, height: u32, text: &str) -> Button {
|
||||
Button {
|
||||
width,
|
||||
height,
|
||||
text: String::from(text),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Draw for Button {
|
||||
fn draw(&self) {
|
||||
println!(
|
||||
"This is a Button, draw by {}x{} : {}",
|
||||
self.width, self.height, self.text
|
||||
);
|
||||
}
|
||||
}
|
32
p16.fearless_conscurrency/shared_trait/src/main.rs
Executable file
32
p16.fearless_conscurrency/shared_trait/src/main.rs
Executable file
@ -0,0 +1,32 @@
|
||||
use shared_trait::*;
|
||||
|
||||
struct SelectBox<'a> {
|
||||
width: i32,
|
||||
height: u32,
|
||||
option: Vec<&'a str>,
|
||||
}
|
||||
|
||||
impl<'a> Draw for SelectBox<'a> {
|
||||
fn draw(&self) {
|
||||
println!(
|
||||
"This is a Button, draw by {}x{} : {:?}",
|
||||
self.width, self.height, self.option
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
println!("Hello, world!");
|
||||
let mut screen = Screen::new();
|
||||
|
||||
let button = Button::new(30, 40, "Button text");
|
||||
screen.add(Box::new(button));
|
||||
screen.add(Box::new(SelectBox {
|
||||
width: 100,
|
||||
height: 300,
|
||||
option: vec!["option1", "option2", "option3"],
|
||||
}));
|
||||
|
||||
// screen.add(Box::new(String::from("asdad"))); //the trait bound `String: shared_trait::Draw` is not satisfied
|
||||
screen.run();
|
||||
}
|
Reference in New Issue
Block a user