覆盖Rust中的全面特征实现

时间:2020-05-25 21:42:32

标签: rust

对于我的游戏规则引擎,我有一个称为Rule的中心特征,它可以处理游戏回调。 Rule有两种类型:BaseRule适用于游戏中的任何实体,而CreatureRule仅适用于生物。我目前的代码结构如下:

trait BaseRule<T> {
    fn on_turn_start(&self, owner: &T) {}
}

#[typetag::serde(tag = "type")]
pub trait CreatureRule: BaseRule<Creature> {
    fn on_death(&self, owner: &Creature) {}
}

这很好,但是有点烦人,因为您需要为每个实现同时实现RuleCreatureRule。我试图全面实施BaseRule

impl<R: CreatureRule> BaseRule<Creature> for R {
}

,但是如果我尝试添加BaseRule特征的新实现,例如,这会带来冲突。通过

impl BaseRule<Creature> for BaseMeleeDamageAttack {
    fn on_turn_start(&self, owner: &Creature) {
        // do stuff
    }
}

因为不能有两个具有相同特征的实现。有没有办法为实现BaseRule的类型提供CreatureRule的全面默认实现,但仍然允许它们覆盖函数的默认实现?

(如果可能,我希望避免在CreatureRule上使用泛型类型参数,因为Serde序列化不适用于具有泛型类型的特征。)

1 个答案:

答案 0 :(得分:1)

我认为您必须为每个手工实现它,但这只是一行:

impl BaseRule<Creature> for ... {}

自动实现将需要一个宏(这将使代码的可读性降低)或隐含的特殊化(rust-lang/rfcs#1210rust-lang/rust#31844),这通常需要每晚执行。

相关问题