不能借用“cells”作为不可变的,因为它也被借用为可变的

问题描述 投票:0回答:1

我遇到了一个典型的借用检查器错误,我希望人们可以向我展示一些惯用的解决方案。下面请看一个微型示例。

#[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
中释放。

rust copy move borrow-checker vec
1个回答
0
投票

有多种方法可以实现这一点。最简单的可能是使用

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);
© www.soinside.com 2019 - 2024. All rights reserved.