我试图从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);
}
Run Code Online (Sandbox Code Playgroud)
目前,这无法使用以下编译器错误构建:
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 }
Run Code Online (Sandbox Code Playgroud)
不幸的是,我需要能够获得两者的可变引用,以便我可以在Piece.exec方法中修改它们.任何想法,还是我试图以错误的方式做到这一点?
Rust无法保证在编译时get_mut不会相互借用相同的元素两次,因此get_mut可变地借用整个向量.
相反,使用切片
pieces.as_slice().split_at_mut(1) 是你想在这里使用的.