2014-10-16 52 views
5

我試圖從Vec中提取兩個元素,該元素將始終包含至少兩個元素。這兩個元素需要以可變的方式提取,因爲我需要能夠在一個操作中更改兩者的值。如何從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方法中修改它們。任何想法,或者我想以錯誤的方式做到這一點?

回答

8

生鏽不能保證在編譯時get_mut是不會可變地借兩次相同的元素,所以get_mut可變地借用整個向量。

相反,使用slices

pieces.as_slice().split_at_mut(1)是你想在這裏用什麼。

+0

這太好了 - 似乎已經做到了。非常感謝。 – 2014-10-17 06:33:17

+1

@DavidEdmonds:'mut_shift_ref'也很有用(例如,可以用來遍歷所有對) – sellibitze 2014-10-17 23:39:56