对于我的游戏规则引擎,我有一个称为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) {}
}
这很好,但是有点烦人,因为您需要为每个实现同时实现Rule
和CreatureRule
。我试图全面实施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序列化不适用于具有泛型类型的特征。)
答案 0 :(得分:1)
我认为您必须为每个手工实现它,但这只是一行:
impl BaseRule<Creature> for ... {}
自动实现将需要一个宏(这将使代码的可读性降低)或隐含的特殊化(rust-lang/rfcs#1210和rust-lang/rust#31844),这通常需要每晚执行。