【发布时间】:2021-07-22 16:21:16
【问题描述】:
我正在尝试通过在我的项目中使用 Rust 来学习它。 但是,我在一些与以下形式非常相似的代码中一直在努力使用借用检查器:
use std::collections::HashMap;
use std::pin::Pin;
use std::vec::Vec;
struct MyStruct<'a> {
value: i32,
substructs: Option<Vec<Pin<&'a MyStruct<'a>>>>,
}
struct Toplevel<'a> {
my_structs: HashMap<String, Pin<Box<MyStruct<'a>>>>,
}
fn main() {
let mut toplevel = Toplevel {
my_structs: HashMap::new(),
};
// First pass: add the elements to the HashMap
toplevel.my_structs.insert(
"abc".into(),
Pin::new(Box::new(MyStruct {
value: 0,
substructs: None,
})),
);
toplevel.my_structs.insert(
"def".into(),
Pin::new(Box::new(MyStruct {
value: 5,
substructs: None,
})),
);
toplevel.my_structs.insert(
"ghi".into(),
Pin::new(Box::new(MyStruct {
value: -7,
substructs: None,
})),
);
// Second pass: for each MyStruct, add substructs
let subs = vec![
toplevel.my_structs.get("abc").unwrap().as_ref(),
toplevel.my_structs.get("def").unwrap().as_ref(),
toplevel.my_structs.get("ghi").unwrap().as_ref(),
];
toplevel.my_structs.get_mut("abc").unwrap().substructs = Some(subs);
}
编译时,我收到以下消息:
error[E0502]: cannot borrow `toplevel.my_structs` as mutable because it is also borrowed as immutable
--> src/main.rs:48:5
|
44 | toplevel.my_structs.get("abc").unwrap().as_ref(),
| ------------------- immutable borrow occurs here
...
48 | toplevel.my_structs.get_mut("abc").unwrap().substructs = Some(subs);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^--------------------
| |
| mutable borrow occurs here
| immutable borrow later used here
我想我明白为什么会发生这种情况:toplevel.my_structs.get_mut(...) 借用 toplevel.my_structs 为可变的。然而,在同一个区块中,toplevel.my_structs.get(...) 也借用了toplevel.my_structs(尽管这次是不可变的)。
我还看到如果借用 &mut toplevel.my_structs 的函数添加一个新密钥,这确实会成为一个问题。
但是,在&mut toplevel.my_structs 借用中所做的只是修改与特定键对应的值,这不应该改变内存布局(这是有保证的,感谢Pin)。对吧?
有没有办法将它传达给编译器,以便我可以编译这段代码?这似乎有点类似于激发hashmap::Entry API 的原因,但我还需要能够访问其他密钥,而不仅仅是我想要修改的那个。
【问题讨论】:
标签: rust borrow-checker