父 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
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
开发者 @ 社科大
文章
134
粉丝
24
喜欢
101
收藏
55
排名:106
访问:8.9 万
私信
所有博文
社区赞助商