【发布时间】:2021-05-15 22:55:41
【问题描述】:
我必须对键进行迭代,通过键在 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 迫使以一种有意义的不同方式思考)或解决它的任何建议?
PS。代码还有一些其他的问题,但让我们先拆分问题并解决这个问题。
【问题讨论】:
-
我已编辑问题以包含完整的错误消息并撤销了我的反对意见。