Complex composition implementation

Hello world. To illustrate my issue, let say I'm creating the tree of living beings. I would like to have something like:

struct Living {
    chromosomes_num: u8,
    environment: Environment
}

struct Animal {
    // Living's fields
    diet: Diet,
    mating_season_begin: Date
    mating_season_end: Date
}

struct Mamal {
    // Animal's fields
    utters_num: u8,
    fedding_duration: u8 // Number of months
}

Knowing that the tree can grow larger and larger, I find no good composition pattern for sharing fields between structs.

What good pattern can I apply in such case ?

What on earth is the advantage of not implementing inheritance in Rust ?

The only thing I can recommend is embedding. You can have traits for the "parent classes" and implement them in the child by forwarding, and use supertraits and trait objects to get trait inheritance. But you know probably already knew that. :slight_smile: I agree it is not convenient, when you really need implementation inheritance. I haven't needed it for my Rust work, but I also know it is sometimes needed.

What on earth is the advantage of not implementing inheritance in Rust ?

Rather than try to debate that I would prefer to say that it is being worked on, although I don't think there is a projected completion date yet.

2 Likes

Rust doesn't have inheritence, but it does have composition.

struct Living {
    chromosomes_num: u8,
    environment: Environment
}

struct Animal {
    base: Living,
    diet: Diet,
    mating_season_begin: Date
    mating_season_end: Date
}

struct Mamal {
    base: Animal,
    utters_num: u8,
    fedding_duration: u8 // Number of months
}

The painful bit about this is that Rust doesn't really provide any quality-of-life tools for working with composition. I am, as I write this, taking a break from solving this exact problem in some code I'm working on (no, the solution is not generally applicable, sorry).

What I wouldn't do to have D's mixin in Rust...

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.