Google News
logo
Rust - Interview Questions
How do you implement inheritance in Rust?
In Rust, there is no direct concept of class-based inheritance as found in some other programming languages. Rust uses a different approach called "trait inheritance" or "trait composition" to achieve similar functionality.

Trait inheritance in Rust allows you to define traits that inherit methods from other traits. This enables you to create hierarchies of traits and build reusable behavior by combining traits together.

Here's an example of how to implement trait inheritance in Rust :
trait Printable {
    fn print(&self);
}

trait Debuggable: Printable {
    fn debug(&self);
}​

In this example :
* The `Printable` trait declares a single method, `print()`.
* The `Debuggable` trait inherits from the `Printable` trait using the `: Printable` syntax.
* The `Debuggable` trait adds an additional method, `debug()`.

With trait inheritance, types that implement the `Debuggable` trait must provide implementations for both the `print()` method inherited from `Printable` and the `debug()` method defined in the `Debuggable` trait.
Here's an example of implementing the `Debuggable` trait for a type :
struct Person {
    name: String,
}

impl Printable for Person {
    fn print(&self) {
        println!("Name: {}", self.name);
    }
}

impl Debuggable for Person {
    fn debug(&self) {
        println!("Debug info: {:?}", self);
    }
}​

In this example, the `Person` struct implements both the `Printable` and `Debuggable` traits. It provides the required implementations for the `print()` and `debug()` methods.

Trait inheritance allows you to organize and reuse behavior by composing traits together. By inheriting from other traits, you can build trait hierarchies that define a set of shared methods and requirements. Types can then implement these traits to provide the necessary behavior.
Advertisement