gpt4 book ai didi

rust - 与可变借用相关的不可变借用导致 "cannot borrow ` *self` 一次多次可变”

转载 作者:行者123 更新时间:2023-11-29 07:44:50 24 4
gpt4 key购买 nike

我正在通过练习学习 Rust。在此文件中,目标是像在电子表格中一样更新单元格:当值更改时,必须重新计算从中派生的所有单元格。在这里,那些被称为该细胞的 parent 。

更新单元格值证明没有问题,但更新 parent 让我与借用检查器作斗争。当我从 HashMap 中检索单元格并更新值时,我不再需要可变引用 - 所以我尝试将其包装在不可变引用中。这样我只需找到它一次。

但 Rust 似乎认为自从我最初从借用的 &mut self 获得我的不可变引用以来,它仍然必须与它相关联。这显然会阻止我再次使用 self

use std::collections::HashMap;
use std::vec::Vec;

struct Cell {
value: i32,
parents: Vec<u32>,
}

pub struct Sheet {
table: HashMap<u32, Cell>,
}

impl Sheet {
pub fn set_value(&mut self, identifier: u32, new_value: i32) {
let mut updated_cell: Option<&Cell> = None;
if let Some(cell) = self.table.get_mut(&identifier) {
let Cell { value, .. } = cell;
*value = new_value;
updated_cell = Some(cell);
}
if let Some(cell) = updated_cell {
recalculate(self, &cell.parents);
}
}
}

fn recalculate(_sheet: &mut Sheet, _cells: &[u32]) {}
error[E0499]: cannot borrow `*self` as mutable more than once at a time
--> src/lib.rs:20:16
|
16 | if let Some(cell) = self.table.get_mut(&identifier) {
| ---------- first mutable borrow occurs here
...
22 | recalculate(self, &cell.parents);
| ^^^^ ------------- first borrow later used here
| |
| second mutable borrow occurs here

我想知道是否有解决方案可以避免第二次搜索或进行不必要的矢量复制。我多次尝试调整代码,但我还没有完全理解所有语法。

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com