父 trait

父 trait#

  • Rust 没有 “继承”,但可以将一个 trait 定义为另一个 trait 的超集(即父 trait)
trait Person {
    fn name(&self) -> String;
}

trait Student: Person {
    fn university(&self) -> String;
}

trait Programer {
    fn fav_language(&self) -> String;
}

trait CompSciStudent: Programer + Student {
    fn git_username(&self) -> String;
}

struct P;

impl CompSciStudent for P {
    fn git_username(&self) -> String {
        "zhisan.git".to_owned()
    }
}

impl Person for P {
    fn name(&self) -> String {
        "zhangsan".to_owned()
    }
}

impl Programer for P {
    fn fav_language(&self) -> String {
        "history".to_owned()
    }
}

impl Student for P {
    fn university(&self) -> String {
        "Baida".to_owned()
    }
}

fn comp_sci_student_greeting(student: &dyn CompSciStudent) -> String {
    format!(
        "My name is {} and I attend {}. My favorite language is {}.My GitHub username is {}",
        student.name(),
        student.university(),
        student.fav_language(),
        student.git_username()
    )
}

fn main() {
    let p = P;
    let s = comp_sci_student_greeting(&p);
    println!("{}", s);
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
pardon110
开发者 @ 社科大
文章
135
粉丝
24
喜欢
103
收藏
56
排名:105
访问:8.9 万
私信
所有博文
社区赞助商