我有一个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
and Vec<i32>
。有解决办法吗?