Rust trait默认实现

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

你可能感兴趣的:(rust)