如何从生锈的Vec中提取两个可变元素

时间:2014-10-16 16:22:27

标签: rust

我试图从Vec中提取两个元素,它总是至少包含两个元素。这两个元素需要可变地提取,因为我需要能够在单个操作中更改两者的值。

示例代码:

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);
}

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

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方法中修改它们。任何想法,或者我试图以错误的方式做到这一点?

1 个答案:

答案 0 :(得分:9)

Rust在编译时不能保证get_mut不会两次可变地借用相同的元素,因此get_mut可以可靠地借用整个向量。

相反,请使用slices

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