Rust Program to Implement multiple inheritance


Implement multiple inheritance

Rust Programming Language


Implement multiple inheritance


Problem


Rust does not support multiple inheritance directly, but there are ways to achieve similar functionality through traits and composition. Here's an example program that demonstrates how to implement multiple inheritance-like functionality in Rust.

Input


trait Foo {
    fn foo(&self) -> String;
}

trait Bar {
    fn bar(&self) -> String;
}

struct Baz {
    foo: Box<dyn Foo>,
    bar: Box<dyn Bar>,
}

impl Baz {
    fn new<T: 'static + Foo, U: 'static + Bar>(foo: T, bar: U) -> Self {
        Self {
            foo: Box::new(foo),
            bar: Box::new(bar),
        }
    }
}

impl Foo for Baz {
    fn foo(&self) -> String {
        self.foo.foo()
    }
}

impl Bar for Baz {
    fn bar(&self) -> String {
        self.bar.bar()
    }
}

struct FooImpl;

impl Foo for FooImpl {
    fn foo(&self) -> String {
        "foo from FooImpl".into()
    }
}

struct BarImpl;

impl Bar for BarImpl {
    fn bar(&self) -> String {
        "bar from BarImpl".into()
    }
}

fn main() {
    let baz = Baz::new(FooImpl, BarImpl);
    println!("{}", baz.foo());
    println!("{}", baz.bar());
}{codeBox}


Output


foo from FooImpl
bar from BarImpl{codeBox}


Explanation


In this example, we define two traits, Foo and Bar, each of which defines a single method. We then define a struct Baz that contains two fields, each of which is a boxed trait object that implements the corresponding trait. This allows Baz to implement both Foo and Bar, effectively achieving multiple inheritance.

We also define implementations of Foo and Bar for Baz, which simply delegate to the corresponding methods on the contained trait objects.

Finally, we define two implementations of the Foo and Bar traits, FooImpl and BarImpl, respectively. These implementations are used to create a Baz object in the main() function, which we then call the foo() and bar() methods on.


Post a Comment