我必须迭代键,在HashMap中按键查找值,可能会在找到的 struct 中作为值进行一些繁重的计算(lazy=>;mutate the struct),然后缓存并以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
和 struct ),因为可能的计算会改变它
有没有关于如何改变设计的建议(因为Rust 迫使人们以一种有意义的不同方式思考)或解决它的建议?
另外,代码还有一些其他问题,但是让我们先把问题分开,解决这个问题.