gpt4 book ai didi

rust - 覆盖Rust中的一揽子特质实现

转载 作者:行者123 更新时间:2023-12-03 11:30:56 25 4
gpt4 key购买 nike

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

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

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

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

最佳答案

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

impl BaseRule<Creature> for ... {}

自动实现将需要一个宏(这将使代码的可读性降低)或隐式特化( rust-lang/rfcs#1210rust-lang/rust#31844),当前需要每晚执行一次。

关于rust - 覆盖Rust中的一揽子特质实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62011235/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com