改变结构)并将其缓存在 Rust 中返回。 我收到以下错误消息: error[E0499]: -6ren">
gpt4 book ai didi

rust - 如何在 Rust 中修复 ".. was mutably borrowed here in the previous iteration of the loop"?

转载 作者:行者123 更新时间:2023-12-03 11:23:53 27 4
gpt4 key购买 nike

我必须迭代键,通过键在 HashMap 中找到值,可能在找到的结构中作为值进行一些繁重的计算(惰性 => 改变结构)并将其缓存在 Rust 中返回。
我收到以下错误消息:

error[E0499]: cannot borrow `*self` as mutable more than once at a time
--> src/main.rs:25:26
|
23 | fn it(&mut self) -> Option<&Box<Calculation>> {
| - let's call the lifetime of this reference `'1`
24 | for key in vec!["1","2","3"] {
25 | let result = self.find(&key.to_owned());
| ^^^^ `*self` was mutably borrowed here in the previous iteration of the loop
...
28 | return result
| ------ returning this value requires that `*self` is borrowed for `'1`
这是 code in playground
use std::collections::HashMap;

struct Calculation {
value: Option<i32>
}

struct Struct {
items: HashMap<String, Box<Calculation>> // cache
}

impl Struct {
fn find(&mut self, key: &String) -> Option<&Box<Calculation>> {
None // find, create, and/or calculate items
}

fn it(&mut self) -> Option<&Box<Calculation>> {
for key in vec!["1","2","3"] {
let result = self.find(&key.to_owned());
if result.is_some() {
return result
}
}
None
}
}
  • 我无法避免循环,因为我必须检查多个键
  • 我必须让它可变(self 和结构),因为可能的计算会改变它

  • 关于如何改变设计(因为 Rust 迫使以一种有意义的不同方式思考)或解决它的任何建议?
    PS。代码还有一些其他问题,但让我们先拆分问题并解决这个问题。

    最佳答案

    您不能使用独占访问进行缓存。您不能将 Rust 引用视为通用指针(顺便说一句:&String&Box<T> 是双重间接,在 Rust 中非常不习惯。使用 &str&T 进行临时借用)。&mut self意味着不只是可变的,而是排他的和可变的,所以你的缓存支持只返回一项,因为它返回的引用必须保持 self只要它存在就“锁定”。
    您需要让借用检查员相信 find下次调用时返回不会突然消失。目前没有这样的保证,因为接口(interface)不会阻止你调用例如items.clear() (借用检查器检查函数的接口(interface)允许什么,而不是函数实际执行什么)。
    您可以使用 Rc 来做到这一点。 ,或使用实现 a memory pool/arena 的 crate .

    struct Struct {
    items: HashMap<String, Rc<Calculation>>,
    }

    fn find(&mut self, key: &str) -> Rc<Calculation>
    这样,如果您克隆 Rc ,它会在需要的时间内存活,与缓存无关。
    您还可以通过内部可变性使其更好。
    struct Struct {
    items: RefCell<HashMap<…
    }
    这将允许您内存 find使用共享借用而不是独占借用的方法:
    fn find(&self, key: &str) -> …
    对于方法的调用者来说,这更容易使用。

    关于rust - 如何在 Rust 中修复 ".. was mutably borrowed here in the previous iteration of the loop"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66167634/

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