1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
|
pub trait GetInformation { fn get_name(&self) -> &String; fn get_age(&self) -> u32; } trait SchoolName { fn get_school_name(&self) -> String { String::from("HongXing School") } }
pub struct Student { pub name: String, pub age: u32, }
impl SchoolName for Student { } impl GetInformation for Student { fn get_name (&self) -> &String { &self.name } fn get_age(&self) -> u32 { self.age } } pub struct Teacher { pub name:String, pub age: u32, pub subject: String, } impl GetInformation for Teacher { fn get_name (&self) -> &String { &self.name } fn get_age(&self) -> u32 { self.age } } impl SchoolName for Teacher { fn get_school_name(&self) -> String { String::from("Guangmingschool") } }
fn print_information(item: impl GetInformation) { println!("name = {}",item.get_name()); println!("age = {}",item.get_age());
} fn main() { let s = Student{name:"xiaoming".to_string(),age:10}; let t = Teacher{name:"xiaohu".to_string(),age:30,subject: "math".to_string}; println!("student, name = {},age = {}",s.get_name(),s.get_age()); println!("student, name = {},age = {}",t.get_name(),t.get_age()); let s_school_name = s.get_school_name(); println!("student school name = {}",s_school_name); let t_school_name = t.get_school_name(); print_information(s); print_information(t); }
|