rust trait(特征)

rust特征小示例

 1 #[derive(Debug)]
 2 pub struct User{
 3     pub name:String,
 4     pub gender: bool,
 5     pub age:u8,
 6 }
 7 // 特征(接口)
 8 pub trait Cheat{
 9     fn new(name:String,gender:bool,age:u8) -> Self;
10     fn get_name(&self) -> String;
11     fn get_age(&self) -> u8;
12 }
13 
14 impl Cheat for User{
15     // 关联函数
16     fn new(name:String,gender:bool,age:u8) -> User{
17         User{
18             name:name,
19             gender:gender,
20             age:age,
21         }
22     }
23     
24     // 方法
25     fn get_name(&self) -> String{
26         self.name.clone()
27     }
28     fn get_age(&self) -> u8{
29         self.age
30     }
31 }
32 //实现了xx特征的类型作为函数参数
33 pub fn show_impl(tmp:&impl Cheat){
34     println!("name :{}",tmp.get_name());
35     println!("age: {}",tmp.get_age());
36 }
37 // 返回数据类型,此类型实现了xx特征
38 pub fn ret() -> impl Cheat{
39     User{
40         name:"def".to_string(),
41         gender:false,
42         age:59
43     }
44 }
45 fn main(){
46     let ur = User::new("bob".to_string(),true,18);
47     println!["{:#?}",ur];
48     println!("name is {},age {}",ur.get_name(),ur.get_age());
49 
50     show_impl(&ur);
51 
52     let _rec =ret();
53 }

 

posted @ 2022-03-18 14:50  天使不设防  阅读(52)  评论(0编辑  收藏  举报