Rust编程2026-02-27 01:00
如何根据类型参数声明不同的方法
rustfan
作者
我有一个 Player 结构体,其中包含一些通用属性,包括 Strategy 属性,而 Strategy 也是一个独立的结构体。我的问题是,我如何根据选择的策略来 impl 不同的方法?我希望找到一种在对象创建时执行的方法,因为 Strategy 属性是常量。我目前使用了一个通用的 impl 块,并使用 match 语句,如下所示:
impl Player {
// turns_vector 是一个全局变量,用于跟踪决策
fn take_turn(self: Player, turns_vector: Vec<(bool, bool)>) -> bool {
match self.strategy {
Strategy::strategy1 => {//一些代码...},
Strategy::strategy2 => {//更多代码...}
}
}
}
但是,如果我理解正确的话,这意味着每次轮次都需要进行评估,因此我想知道是否有办法只声明一次方法,然后始终使用该方法。
31