我需要对一个struct字段的不可变访问和对另一个struct字段的可变访问,但它们必须相互堆叠。我多次遇到这个问题而且我不知道如何解决这个问题。
use std::collections::HashMap;
struct Bar;
impl Bar {
fn get(&self) -> i32 {
100
}
}
struct Foo {
chars: HashMap<char, i32>,
b: Bar,
}
impl Foo {
fn run(&mut self) {
self.chars.entry('c').or_insert_with(|| self.b.get() * 100);
}
}
fn main() {
let mut m = Foo {
chars: HashMap::new(),
b: Bar,
};
m.run();
}
error[E0502]: cannot borrow `self` as immutable because `self.chars` is also borrowed as mutable
--> src/main.rs:16:46
|
16 | self.chars.entry('c').or_insert_with(|| self.b.get() * 100);
| ---------- ^^ ---- - mutable borrow ends here
| | | |
| | | borrow occurs due to use of `self` in closure
| | immutable borrow occurs here
| mutable borrow occurs here
答案 0 :(得分:6)
问题在于你正试图以可变的方式借用PHP Fatal error: Uncaught exception 'MongoWriteConcernException'
with message 'localhost:27017: location object expected, location array
not in correct format' in /var/www/html/muyal/cli/tasks/MedicineTask.php:51
和,正如编译器所说的那样。作为pointed out by Stefan,借用检查器无法区分跨越闭包边界的字段访问,因此我们需要通过更明确地了解我们想要借用并传递给闭包来帮助它。
执行此操作的方法是取出对self
的引用,并在self.b
内使用
or_insert_with()