我需要遍历键,通过键在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`
这里是代码演示。
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 强制以有些不同的方式思考),或者解决它的方法吗?
附言:代码中还有其他问题,但让我们先分割问题并解决这个。
result
的生命周期也结束了。所以,“为什么”和“在循环的上一个迭代中被可变地借用”是一个错误,如果它不是错误,我们如何错误地使用它。即使简要解释也会有所帮助,这个错误让我感到困惑:' ) - AdityaG15