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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| #[derive(Debug)]
fn print_information(item: impl GetInformation) { println!("name = {}",item.get_name()); println!("age = {}",item.get_age()); }
fn print_information<T: GetInfromation>(item: T) { println!("name = {}",item.get_name()); println!("age = {}",item.get_age()); } trait GetName { fn get_name(&self) -> &String; } trait GetAge { fn get_age(&self) -> u32; }
fn print_information<T: GetName+Get>(item: T) { println!("name = {}",item.get_name()); println!("age = {}",item.get_age());
}
pub struct Student { pub name: String, pub age: u32, } pub struct Teacher { pub name: String, pub age: u32, } impl GetName for Student { fn get_name(&self) -> &String { &self.name } } impl GetName for Teacher { fn get_name(&self) -> &String { &self.name } }
impl GetAge for Student { fn get_age(&self) -> &String { &self.age } } impl GetAge for Teacher { fn get_age(&self) -> &String { &self.age } }
fn produce_item_with_age() -> impl GetAge {
Student { name: String::from("xiaoming"), age: 15,
} } fn main() { let s = Student {name: "xiaoming".to_string(),age: 10}; print_information(s); let s = produce_item_with_age();
}
|