如何从 Rust 中的 Vec 中提取两个可变元素 [英] How do I extract two mutable elements from a Vec in rust

查看:61
本文介绍了如何从 Rust 中的 Vec 中提取两个可变元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 Vec 中提取两个元素,它始终至少包含两个元素.这两个元素需要可变地提取,因为我需要能够在单个操作中更改它们的值.

I'm trying to extract two elements from a Vec, which will always contain at least two elements. These two elements need to be extracted mutably as I need to be able to change values on both as part of a single operation.

示例代码:

struct Piece {
  x: u32,
  y: u32,
  name: &'static str
}

impl Piece {
  fn exec(&self, target: &mut Piece) {
    println!("{} -> {}", self.name, target.name)
  }
}

struct Board {
  pieces: Vec<Piece>
}

fn main() {
    let mut board = Board {
      pieces: vec![
        Piece{ x: 0, y: 0, name: "A" },
        Piece{ x: 1, y: 1, name: "B" }
      ]
    };

    let mut a = board.pieces.get_mut(0);
    let mut b = board.pieces.get_mut(1);
    a.exec(b);
}

目前,这无法通过以下编译器错误构建:

At present, this fails to build with the following compiler errors:

piece.rs:26:17: 26:29 error: cannot borrow `board.pieces` as mutable more than once at a time
piece.rs:26     let mut b = board.pieces.get_mut(1);
                            ^~~~~~~~~~~~
piece.rs:25:17: 25:29 note: previous borrow of `board.pieces` occurs here; the mutable borrow prevents subsequent moves, borrows, or modification of `board.pieces` until the borrow ends
piece.rs:25     let mut a = board.pieces.get_mut(0);
                            ^~~~~~~~~~~~
piece.rs:28:2: 28:2 note: previous borrow ends here
piece.rs:17 fn main() {
...
piece.rs:28 }

不幸的是,我需要能够获得对两者的可变引用,以便我可以在 Piece.exec 方法中修改两者.有什么想法,还是我试图以错误的方式做到这一点?

Unfortunately, I need to be able to obtain a mutable reference to both so that I can modify both within the Piece.exec method. Any ideas, or am I trying to do this the wrong way?

推荐答案

Rust 不能在编译时保证 get_mut 不会可变地借用同一个元素两次,所以 get_mut 可变地借用整个向量.

Rust can't guarantee at compile time that get_mut is not going to mutably borrow the same element twice, so get_mut borrows the entire vector mutably.

改为使用切片

pieces.as_slice().split_at_mut(1) 是你想在这里使用的.

pieces.as_slice().split_at_mut(1) is what you want to use here.

这篇关于如何从 Rust 中的 Vec 中提取两个可变元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆