Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share same implementation and maybe share fields

How can I simplify this code? I still can't wrap my head around rust's traits and structs after OOP.

struct Player {
    entity: Entity,
    hp: i32,
    atk: i32
}

struct Chest {
    entity: Entity,
    amount: i32
}

impl Drawable for Chest {
    fn draw(&self, mut pencil: Pencil) {
        pencil.draw(&self.entity);
    }
}

impl Drawable for Player {
    fn draw(&self, mut pencil: Pencil) {
        pencil.draw(&self.entity);
    }
}

Maybe there is a way to inherit some fields like in OOP?

Also, if anybody knows a good and clear tutorial about traits and structs in rust, I would be very glad if you shared it!

like image 650
salat _ Avatar asked Jul 26 '26 03:07

salat _


1 Answers

In my experience, typically when you want to "share attributes" like this you typically want to break the structs into their own types and implement the traits you need on each.

Consider if your structs looked like this:

struct DrawableEntity {
    entity: Entity,
    ... // other stuff you might need to draw
}

struct Chest {
    drawable: DrawableEntity,
    ...
}

struct Player {
    drawable: DrawableEntity,
    ...
}

impl Drawable for DrawableEntity { ... }

Then in your code it might look like this:

player.drawable.draw(mut pencil);
chest.drawable.draw(mut pencil);
like image 80
wannabe Avatar answered Jul 28 '26 20:07

wannabe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!