Rust trait默认实现

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 20:40   1091   0
trait SchoolName {
    fn get_school_name(&self) -> String {
        String::from("HongXingSchool")
    }
}

pub struct Student {
    pub name: String,
    pub age: u32,
}

impl SchoolName for Student {}

pub struct Teacher {
    pub name: String,
    pub age: u32,
    pub subject: String,
}

impl SchoolName for Teacher { //不使用默认实现
    fn get_school_name(&self) -> String {
        format!("I'm teacher {}, from HongXingSchool", self.name)
    }
}

fn main() {
    let s = Student { name: "xiaoming".to_string(), age: 10 };
    let t = Teacher { name: "xiaohuang".to_string(), age: 30, subject: String::from("math") };
    let s_school_name = s.get_school_name();
    println!("student school name = {}", s_school_name);
    let t_school_name = t.get_school_name();
    println!("teacher school name = {}", t_school_name);
}

cargo run:

student school name = HongXingSchool
teacher school name = I'm teacher xiaohuang, from HongXingSchool

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP