我遇到了一个典型的借用检查器错误,我希望人们可以向我展示一些惯用的解决方案。下面请看一个微型示例。
#[derive(Debug)]
pub struct Cell {
ploidy: u32,
}
impl Cell {
fn from_ploidy(ploidy: u32) -> Self {
Cell { ploidy }
}
fn hybrid(&mut self, cell: Cell) { // I would like `cell` to be consumed.
self.ploidy += cell.ploidy;
}
}
fn main() {
let mut cells = vec![
Cell::from_ploidy(46), Cell::from_ploidy(40),
Cell::from_ploidy(46), Cell::from_ploidy(40)
];
println!("{:?}", cells);
// To hybrid every two consecutive cells
// e.g. cells[0].hybrid(cells[1]);
// cells[2].hybrid(cells[3]);
// and let go cells[1] and cells[3]
for i in 0..2usize {
cells[i*2].hybrid(cells[i*2+1]);
}
println!("{:?}", cells);
}
错误是
cannot borrow `cells` as immutable because it is also borrowed as mutable
immutable borrow occurs here
基本上我希望将
cells[1]
、cells[3]
的资源移至cells[0]
、cells[2]
,同时将cells[1]
、cells[3]
本身从cells
中释放。
itertools
的 chunks()
:
use itertools::Itertools;
let cells = cells
.into_iter()
.chunks(2)
.into_iter()
.map(|mut chunk| {
let mut a = chunk.next().unwrap();
let b = chunk.next().unwrap();
a.hybrid(b);
a
})
.collect::<Vec<_>>();
println!("{:?}", cells);