struct - Rust 特征状态

标签 struct rust code-duplication traits

我将从 Rust for Rubyist 中的这个怪物“Monster”代码开始:

trait Monster {
    fn attack(&self);
    fn new() -> Self;
}

struct IndustrialRaverMonkey {
    life: int,
    strength: int,
    charisma: int,
    weapon: int,
}

struct DwarvenAngel {
    life: int,
    strength: int,
    charisma: int,
    weapon: int,
} ...
impl Monster for IndustrialRaverMonkey { ...
impl Monster for DwarvenAngel { ...

我担心代码重复。在 Java 中,我将创建定义 attack 方法和基类的接口(interface),其中包含所有参数(lifestrengthcharisma, 武器)。我将在 C++ 中使用抽象类做同样的事情。 我可以找到一些丑陋和不直观的方法来解决这个问题,但是有减少代码的好方法吗?我的意思是,保持它的可扩展性和可读性。

最佳答案

另一种方法,它有利于组合,并且在需要时更容易从中分离实现(例如,DwarvenAngelCharacteristics 需要一个额外的字段):

trait Monster {
    fn attack(&self);
}

struct Characteristics {
    life: int,
    strength: int,
    charisma: int,
    weapon: int,
}

struct IndustrialRaverMonkey {
    characteristics: Characteristics
}

struct DwarvenAngel {
    characteristics: Characteristics
}

fn same_attack(c: Characteristics) {
    fail!("not implemented")
}

impl Monster for IndustrialRaverMonkey {
    fn attack(&self) {
        same_attack(self.characteristics)
    }
}

impl Monster for DwarvenAngel {
    fn attack(&self) {
        same_attack(self.characteristics)
    }
}

或者,您可以用一个枚举来表示您的怪物类型,这与 A.B. 的回答非常相似:

trait Monster {
    fn attack(&self);
}

struct Characteristics {
    life: int,
    strength: int,
    charisma: int,
    weapon: int,
}

enum Monsters {
    IndustrialRaverMonkey(Characteristics),
    DwarvenAngel(Characteristics),
}

fn same_attack(_: &Characteristics) {
    fail!("not implemented")
}

impl Monster for Monsters {
    fn attack(&self) {
        match *self {
            IndustrialRaverMonkey(ref c) => same_attack(c),
            DwarvenAngel(ref c)          => same_attack(c)
        }
    }
}

关于struct - Rust 特征状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22935449/

相关文章:

c - 结构内部计算的极值和

indexing - 遍历扁平化2D Vec列的更有效方法

java - 具有不同修复版本的 Quickfix 重复代码

multithreading - rust tokio::spawn 在 mutexguard 之后等待

rust - Rust 中的所有输入都应该是可变的吗?

javascript - 重构代码——变量作用域

c# - 在对表格、其布局和记录建模时,如何避免代码重复,所有这些都共享相同的基本结构?

c++ - 为什么这个结构需要一个大小值?

C 自由动态结构数组 - 为什么它们没有传染性

c - 读取并存储 C 字符串值