[英]Use trait blanket implementation to restrict type trait bounds in 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) {}
}
这很好用,但有点烦人,因为您需要为每个实现同时实现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
}
}
因为不能有相同特征的两个实现。 有没有办法可以为实现CreatureRule
但仍允许它们覆盖函数的默认实现的类型提供BaseRule
的全面默认实现?
(如果可能的话,我宁愿避免在CreatureRule
上使用泛型类型参数,因为 Serde 序列化不适用于具有泛型类型的特征。)
我认为您必须为每个手动实现它,但它只有一行:
impl BaseRule<Creature> for ... {}
自动实现将需要一个宏(这会使代码的可读性降低),或 impl 专业化( rust-lang/rfcs#1210和rust-lang/rust#31844 ),目前需要每晚。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.