如何实现等级特征?

时间:2018-11-05 22:07:10

标签: rust

我在层次结构中具有两个特征:AnimalBird。如何创建实现Chicken的{​​{1}}?

Bird

playground

当我尝试编译时,我得到:

trait Animal {
    fn noise(&self) -> String;
    fn print_noise(&self) {
        print!("{}", self.noise());
    }
}

trait Bird: Animal {
    fn noise(&self) -> String {
        "chirp"
    }
}

struct Chicken {}

impl Bird for Chicken {}

我不想在error[E0277]: the trait bound `Chicken: Animal` is not satisfied --> src/lib.rs:16:6 | 16 | impl Bird for Chicken {} | ^^^^ the trait `Animal` is not implemented for `Chicken` 之前实现Animal,因为我希望BirdChicken继承noise函数。

1 个答案:

答案 0 :(得分:1)

简单的答案:您不能。 Rust在设计上没有继承。 Rust没有与Java或C ++相同的面向对象模型。

如果您确实想做这样的事情,则可以使用this代码为另一个特征实现一个特征

trait Animal {
    fn noise(&self) -> String;
    fn print_noise(&self) {
        print!("{}", self.noise());
    }
}

trait Bird:Animal {}

impl<T: Bird> Animal for T {
    fn noise(&self) -> String {
        "chirp".to_string()
    }
}


struct Chicken {}

impl Bird for Chicken {}

fn main() {
    let chicken = Chicken{};
    chicken.print_noise();
}

和其他人一样,我建议阅读The Rust Programming Language书,特别是OOPTraits and Generics部分。在线阅读是免费的。