2

I have two traits in a hierarchy: Animal and Bird. How can I create a Chicken that implements Bird?

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 {}

playground

When I try to compile, I get:

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`

I don't want to implement Animal before Bird, because I want Chicken to inherit the noise function from Bird.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
A F
  • 7,424
  • 8
  • 40
  • 52
  • *to inherit the noise function from `Bird`*. Who is going to implement `Animal::noise`? It's **not** the same method as `Bird::noise`. – Shepmaster Nov 05 '18 at 22:09
  • 1
    I believe your question is answered by the answers of [“Subclassing” traits in Rust](https://stackoverflow.com/q/47965967/155423). If you disagree, please [edit] your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Nov 05 '18 at 22:10
  • You should also go back and re-read [Object Oriented Programming Features of Rust](https://doc.rust-lang.org/book/second-edition/ch17-00-oop.html) in *The Rust Programming Language*. – Shepmaster Nov 05 '18 at 22:12

1 Answers1

2

Simple answer: you can't. Rust doesn't have inheritance by design. Rust doesn't have same object-oriented model as Java or C++.

If you really want to do something like this, you can implement one trait for another with this code

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();
}

As others, I would suggest reading The Rust Programming Language book, specifically OOP and Traits and Generics sections. It's free when reading online.

A F
  • 7,424
  • 8
  • 40
  • 52
Shchvova
  • 458
  • 5
  • 15
  • Does this answer mean you agree that the question has already been answered by the proposed duplicate? – Shepmaster Nov 05 '18 at 22:59
  • @Shepmaster its 90% the same answer. However the proposed duplicate is more "multi-class" than "heirarchical-class" (if I'm understanding it correctly) – A F Nov 05 '18 at 23:16