如何共享相同的实现以及共享字段

sal*_*t _ 6 struct traits rust

我怎样才能简化这段代码?在面向对象编程之后,我仍然无法理解 Rust 的特征和结构。

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

也许有一种方法可以像 OOP 中那样继承某些字段?

另外,如果有人知道有关 Rust 特征和结构的良好而清晰的教程,如果您分享它,我将非常高兴!

小智 7

根据我的经验,通常当您想要像这样“共享属性”时,您通常希望将结构分解为它们自己的类型并在每个结构上实现您需要的特征。

考虑一下您的结构是否如下所示:

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

struct Chest {
    drawable: DrawableEntity,
    ...
}

struct Player {
    drawable: DrawableEntity,
    ...
}

impl Drawable for DrawableEntity { ... }
Run Code Online (Sandbox Code Playgroud)

然后在你的代码中它可能看起来像这样:

player.drawable.draw(mut pencil);
chest.drawable.draw(mut pencil);
Run Code Online (Sandbox Code Playgroud)


Jer*_*ows 1

由于您的impl块使用不同的类型执行完全相同的操作,因此您可以将其抽象为宏,以便对任何新Drawable类型重复执行此操作都很简单:

macro_rules! impl_drawable {
    ($t:ty) => {
        impl Drawable for $t {
            fn draw(&self, mut pencil: Pencil) {
                pencil.draw(&self.entity);
            }
        }
    };
}

impl_drawable!(Chest);
impl_drawable!(Player);
Run Code Online (Sandbox Code Playgroud)

Entity然而,这就是我认为你能做的一切,特征不能像 OOP 语言中的抽象类那样拥有字段,所以你不能真正“共享”在结构中拥有 an 的想法。

如果您还没有读过这本书,本书有一章讨论了一些常见的 OOP 模式以及它们如何转换为惯用的 Rust。