重写 Rust 中的总体特征实现

Der*_*urn 5 rust

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

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

这工作正常,但有点烦人,因为您需要为每个实现都实现Rule和CreatureRule。我试图全面实施BaseRule:

impl<R: CreatureRule> BaseRule<Creature> for R {
}
Run Code Online (Sandbox Code Playgroud)

但是如果我尝试添加该BaseRule特征的新实现,例如通过

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

因为同一特征不可能有两个实现。有没有一种方法可以为BaseRule实现的类型提供一揽子默认实现CreatureRule,但仍然允许它们覆盖函数的默认实现?

(如果可能的话,我宁愿避免使用泛型类型参数,CreatureRule因为 Serde 序列化不适用于泛型类型的特征。)

Sol*_*cko 2

我认为你必须为每个手动实现它,但它只有一行:

impl BaseRule<Creature> for ... {}
Run Code Online (Sandbox Code Playgroud)

自动实现需要一个宏(这会使代码的可读性较差)或 impl 专门化(rust-lang/rfcs#1210和rust-lang/rust#31844),目前需要 nightly。