"首次提交"

This commit is contained in:
2024-06-08 15:01:12 +08:00
parent 6e0f708d0a
commit 84349a2469
112 changed files with 3272 additions and 0 deletions

View File

@ -0,0 +1 @@
/target

View 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]

View 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
);
}
}

View 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();
}