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!
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With