【问题标题】:Use of moved value from function implemented on a struct in Rust [duplicate]使用 Rust 结构上实现的函数中的移动值 [重复]
【发布时间】: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 特征,但由于 StringVec&lt;i32&gt; 我不能这样做。有解决办法吗?

【问题讨论】:

  • 请包含add_to_hand 的实现,因为这是此错误的重要部分。听起来好像需要self而不是&amp;self&amp;mut self,这是问题的核心。
  • @loganfsmyth 好的,添加它。那么用&amp;mut self 替换mut self 会解决问题吗?
  • 很难回答您的问题,因为它不包含minimal reproducible example。我们无法分辨代码中存在哪些 crate(及其版本)、类型、特征、字段等。如果您尝试在Rust Playground 上重现您的错误,如果可能的话,这将使我们更容易为您提供帮助,否则在全新的 Cargo 项目中,然后在edit 您的问题中包含附加信息。您可以使用Rust-specific MRE tips 来减少您在此处发布的原始代码。谢谢!

标签: rust borrow-checker borrowing borrow


【解决方案1】:

由于add_to_hand 拥有Player 的所有权,因为它使用mut self,而不是&amp;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-01-11
    • 2021-12-21
    • 1970-01-01
    • 2015-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多