-1

我有一个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特征,但我不能这样做,因为Stringand Vec<i32>。有解决办法吗?

4

1 回答 1

2

由于add_to_hand拥有Player,因为它使用mut self,而不是&mut self,您要么需要:

离开add_to_hand并使用它的返回值,例如

player = player.add_to_hand(deck.draw());

但这很奇怪,因为没有理由改变然后返回播放器,所以你应该这样做

pub fn add_to_hand(&mut self, card: i32) {
    //push to hand
    self.0.push(card);
}

并且您的代码应该按原样工作。

于 2020-03-10T02:57:23.617 回答