[英]Overriding a blanket trait implementation in Rust
For my game rules engine, I have a central trait called Rule
that handles game callbacks.对于我的游戏规则引擎,我有一个名为Rule
的核心特征来处理游戏回调。 There are two types of Rule
s: a BaseRule
applies to any entity in the game, and a CreatureRule
applies only to Creatures. Rule
有两种类型: BaseRule
适用于游戏中的任何实体, CreatureRule
仅适用于 Creature。 I currently structure the code like this:我目前的代码结构如下:
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) {}
}
This works fine, but is slightly annoying because you need to implement both Rule
and CreatureRule
for every implementation.这很好用,但有点烦人,因为您需要为每个实现同时实现Rule
和CreatureRule
。 I tried to make a blanket implementation of BaseRule
:我试图对BaseRule
进行全面实施:
impl<R: CreatureRule> BaseRule<Creature> for R {
}
but this introduces a conflict if I try to add a new implementation of the BaseRule
trait, eg via但是如果我尝试添加BaseRule
特征的新实现,例如通过
impl BaseRule<Creature> for BaseMeleeDamageAttack {
fn on_turn_start(&self, owner: &Creature) {
// do stuff
}
}
since there can't be two implementations of the same trait.因为不能有相同特征的两个实现。 Is there a way I can provide a blanket default implementation of BaseRule
to types that implement CreatureRule
but still allow them to override the default implementation of the functions?有没有办法可以为实现CreatureRule
但仍允许它们覆盖函数的默认实现的类型提供BaseRule
的全面默认实现?
(if possible I'd prefer to avoid having generic type parameters on CreatureRule
since Serde serialization doesn't work for traits with generic types.) (如果可能的话,我宁愿避免在CreatureRule
上使用泛型类型参数,因为 Serde 序列化不适用于具有泛型类型的特征。)
I think you have to manually implement it for each, but it's only one line:我认为您必须为每个手动实现它,但它只有一行:
impl BaseRule<Creature> for ... {}
Automatic implementation would require either a macro (which would make the code less readable), or impl specialization ( rust-lang/rfcs#1210 and rust-lang/rust#31844 ), which would currently require nightly.自动实现将需要一个宏(这会使代码的可读性降低),或 impl 专业化( rust-lang/rfcs#1210和rust-lang/rust#31844 ),目前需要每晚。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.