How to inherit trait method in rust?


#1

Is there anyway to implement inheritance in Rust? I’ve read Extending Traits, as the comment said:

Rust has trait inheritance, it looks like this:

pub trait A {}

pub trait B: A {}

So I tried to implement this Python code in Rust:

class Animal(object):
    @classmethod
    def howl(cls):
        print("ao ao")

class Tiger(Animal):
    @classmethod
    def find_food(cls):
        print("find food")

a = Tiger()
a.howl()
a.find_food()

Rust way: lib.rs

pub trait Animal {
    fn howl(&self) { println!("ao ao"); }
}
pub trait Tiger: Animal {
    fn find_food(&self) { println!("find food"); }
}
impl<'a> Animal for &'a str {}
impl<'a> Tiger for &'a str {}

main.rs

extern crate colorful;
use colorful::Tiger;

fn main() {
    "da".find_food();
//    "da".howl();
}

If I want to use howl I must import Animal trait, and I don’t think this is inheritance, is there a way to import one trait in order to use all method of this trait and subtrait? How can I organize code like this?


#2
pub trait B: A {}

This is not really inheritance. It’s more like “things that implement B also need to implement A”.

The traits remain separate, so you still need to use Animal to use Animal's methods.

Rust isn’t quite an object-oriented language. It has a few similar constructs, but more advanced object-oriented design patterns won’t quite fit in Rust.

Inheritance hierarchies are one of these things. Rust insists on composition over inheritance, so try to “flatten” it to a single trait (or trait per functionality, e.g. Howling, Foraging) and use nested structs instead of inheritance.


#3

Thanks kornel, I agree with that “It’s more like things that implement B also need to implement A.”

And as you said maybe I should use another way to instead inheritance.