【问题标题】:How do I extract two mutable elements from a Vec in rust [duplicate]如何从生锈的 Vec 中提取两个可变元素 [重复]
【发布时间】:2014-10-16 16:22:26
【问题描述】:

我正在尝试从 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 方法中修改两者。有什么想法,还是我试图以错误的方式做到这一点?

【问题讨论】:

    标签: rust


    【解决方案1】:

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

    改为使用slices

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

    【讨论】:

    • 太棒了 - 似乎成功了。非常感谢。
    • @DavidEdmonds: mut_shift_ref 也很有用(例如,可用于循环所有对)
    猜你喜欢
    • 1970-01-01
    • 2022-10-21
    • 2020-12-24
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    • 2021-03-11
    • 2020-09-15
    • 2018-08-30
    相关资源
    最近更新 更多