对于我的游戏规则引擎,我有一个核心特征,称为Rule
处理游戏回调。有两种类型Rule
s: a 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
and 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 序列化不适用于泛型类型的特征。)
我认为你必须为每个手动实现它,但它只有一行:
impl BaseRule<Creature> for ... {}
自动实现需要宏(这会使代码可读性较差)或 impl 专门化(rust-lang/rfcs#1210 https://github.com/rust-lang/rfcs/pull/1210 and rust-lang/rust#31844 https://github.com/rust-lang/rust/issues/31844),目前需要每晚。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)