繁体   English   中英

覆盖 Rust 中的一揽子特征实现

[英]Overriding a blanket trait implementation in Rust

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

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
    }
}

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

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

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

impl BaseRule<Creature> for ... {}

自动实现将需要一个宏(这会使代码的可读性降低),或 impl 专业化( rust-lang/rfcs#1210rust-lang/rust#31844 ),目前需要每晚。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM