【发布时间】:2020-06-21 22:37:39
【问题描述】:
我有一个带有方法的Player 结构。我创建了一个新玩家
并尝试调用该方法:
#[derive(Debug, Default, Clone)]
pub struct Player(pub Vec<i32>, i32, String);
impl Player {
/// Create the player
pub fn new_player() -> Self {
Player(Vec::new(), 0, String::new())
}
}
impl Player {
pub fn add_to_hand(mut self, card: i32) -> Self {
//push to hand
self.0.push(card);
self
}
}
fn main() {
let mut player = Player::new_player();
while (get_total(&player.0) <= 21) && (hit == 'y') {
println!("Want another card? y/n");
hit = read!();
player.add_to_hand(deck.draw());
player.show_hand();
}
}
我明白了:
error[E0382]: borrow of moved value: `player`
let mut player = Player::new_player();
| ---------- move occurs because `player` has type `high_low::player::Player`, which does not implement the `Copy` trait
...
60 | while(get_total(&player.0) <= 21) && (hit == 'y') {
| ^^^^^^^^^ value borrowed here after move
...
63 | player.add_to_hand(deck.draw());
| ------ value moved here, in previous iteration of loop
这只是一个例子,我在整个程序中多次调用函数,因此每次都得到同样的错误。
我知道这是因为结构 Player 没有派生 Copy 特征,但由于 String 和 Vec<i32> 我不能这样做。有解决办法吗?
【问题讨论】:
-
请包含
add_to_hand的实现,因为这是此错误的重要部分。听起来好像需要self而不是&self或&mut self,这是问题的核心。 -
@loganfsmyth 好的,添加它。那么用
&mut self替换mut self会解决问题吗? -
很难回答您的问题,因为它不包含minimal reproducible example。我们无法分辨代码中存在哪些 crate(及其版本)、类型、特征、字段等。如果您尝试在Rust Playground 上重现您的错误,如果可能的话,这将使我们更容易为您提供帮助,否则在全新的 Cargo 项目中,然后在edit 您的问题中包含附加信息。您可以使用Rust-specific MRE tips 来减少您在此处发布的原始代码。谢谢!
标签: rust borrow-checker borrowing borrow