đŸš« Rust Doesn’t Do Class Inheritance — And That’s a Good Thing

·

No inheritance

If you’re coming from an object-oriented language like Java, C++, or C#, one of the first surprises you’ll encounter in Rust is:

There is no class inheritance.
No class Dog extends Animal.
No overriding methods.
No superclass fields.

So
 how the heck do you write reusable, extensible code in Rust?

Turns out, Rust gives you powerful tools that make class inheritance unnecessary — and even undesirable.

Let’s dive into the “why” and “how.”


🧬 Why No Class Inheritance?

Rust’s core values are safety, clarity, and performance. Class inheritance often leads to:

  • Tight coupling between classes
  • Fragile hierarchies that break easily with changes
  • The “diamond problem” in multiple inheritance
  • Hidden dependencies via superclass fields and methods

Rust instead encourages composition over inheritance, meaning:

“Instead of saying ‘is-a’, you say ‘has-a’ or ‘can-do’.”


✅ How to Overcome the Lack of Inheritance

1. Use Structs and Traits

Rust separates data (struct) from behavior (trait), and you can implement multiple traits per struct:

struct Dog {
    name: String,
}

trait Animal {
    fn speak(&self);
}

impl Animal for Dog {
    fn speak(&self) {
        println!("{} says: Woof!", self.name);
    }
}

Want a Cat too? Just implement the same trait:

struct Cat {
    name: String,
}

impl Animal for Cat {
    fn speak(&self) {
        println!("{} says: Meow!", self.name);
    }
}

Now you can treat them both as Animals without inheritance.


2. Trait Objects and Polymorphism

If you want polymorphism like you’d get from inheritance:

fn make_it_talk(animal: &dyn Animal) {
    animal.speak();
}

This is like calling virtual methods in OOP — but explicit and safer.


3. Composition (Structs Inside Structs)

You can embed structs inside other structs for code reuse:

struct Engine {
    power: u32,
}

struct Car {
    engine: Engine,
}

impl Car {
    fn start(&self) {
        println!("Engine starts with {} horsepower!", self.engine.power);
    }
}

You don’t inherit from Engine; you own one.


4. Default Trait Implementations

Traits can define default behavior, which can be overridden:

trait Animal {
    fn speak(&self) {
        println!("(silent animal)");
    }
}

impl Animal for Dog {
    fn speak(&self) {
        println!("Woof!");
    }
}

impl Animal for Cat {} // uses default

5. Enums for Shared Behavior

Rust enums can be used to group types and delegate behavior:

enum Pet {
    Dog(Dog),
    Cat(Cat),
}

impl Pet {
    fn speak(&self) {
        match self {
            Pet::Dog(d) => d.speak(),
            Pet::Cat(c) => c.speak(),
        }
    }
}

This gives you a clean switch-style dispatch.


🧠 Final Thoughts

You don’t need class inheritance in Rust — and that’s liberating.

By using traits for behavior, composition for structure, and enums for polymorphism, Rust gives you flexibility without sacrificing clarity or performance.

Instead of asking:

“How do I simulate inheritance in Rust?”

Ask:

“How can I model my problem in a more composable and safe way?”

Rust’s answer is often simpler — and smarter.

Comments

One response to “đŸš« Rust Doesn’t Do Class Inheritance — And That’s a Good Thing”

  1. vmf Avatar

    📚 Fontes Oficiais e TĂ©cnicas
    Rust Book – “Traits”
    📖 https://doc.rust-lang.org/book/ch10-02-traits.html

    Explica como traits funcionam, incluindo exemplos e comparaçÔes com interfaces.

    Rust Reference – “Traits”
    🧠 https://doc.rust-lang.org/reference/items/traits.html

    Fonte técnica mais detalhada sobre a definição e uso de traits na linguagem.

    Rust by Example – “Traits”
    📘 https://doc.rust-lang.org/rust-by-example/trait.html

    Traz exemplos prĂĄticos e concisos de como implementar e usar traits.

    Blog do Steve Klabnik – “Rust doesn’t have inheritance. Get over it.”
    ✍ https://words.steveklabnik.com/rust-doesnt-have-inheritance-get-over-it

    Um Ăłtimo artigo do core team do Rust explicando a filosofia por trĂĄs da ausĂȘncia de herança.

    “Composition over Inheritance” – Martin Fowler
    đŸ§± https://martinfowler.com/bliki/CompositionOverInheritance.html

    Explica por que composição Ă© geralmente mais saudĂĄvel que herança em design OO — princĂ­pio seguido pelo Rust.

    đŸŽ„ Extras (para estudo complementar)
    “Object-Oriented Programming in Rust” – Jon Gjengset (YouTube)
    đŸ“ș https://www.youtube.com/watch?v=8O0Nt9qY_vo

    Uma explicação moderna e pråtica sobre como usar traits e composição para alcançar OOP em Rust.

    Crate dyn-clone – para quem precisa de objetos clonáveis via dyn Trait
    🧰 https://docs.rs/dyn-clone/

Leave a Reply