在接下来的i中,在接下来的MVE中,我有一个结构
A
,其中包含一个AElem
的向量。每个AElem
包含一个引用其他AElem
的地图。
use std::collections::HashMap;
struct AElem<'b> {
val: HashMap<String, &'b AElem<'b>>,
}
pub struct A<'b> {
data: Vec<AElem<'b>>,
}
impl<'b> A<'b> {
pub fn init() -> A<'b> {
let mut data: Vec<AElem<'b>> = Vec::new();
for _ in 0..10 {
data.push(AElem { val: HashMap::new() });
}
for i in 0..data.len() {
let (left, right) = data.split_at_mut(i);
for j in i - 1..=0 {
right[0].val.insert(format!("{}-{}", i, j), &left[j]);
}
}
println!("{}", data.len());
A { data }
}
}
fn main() {
A::init();
}
主要的挑战在于存储对地图中其他
AElem
s 的引用。为此,我需要两次引用 data
;一个用于操作 val
的可变变量,以及一个我用作地图参考的不可变变量。我使用split_at_mut
实现。然而,我得到了三个编译错误,这对我来说没有意义(在这段代码的上下文中)。
error[E0499]: cannot borrow `data` as mutable more than once at a time
--> src/main.rs:20:33
|
11 | impl<'b> A<'b> {
| -- lifetime `'b` defined here
12 | pub fn init() -> A<'b> {
13 | let mut data: Vec<AElem<'b>> = Vec::new();
| -------------- type annotation requires that `data` is borrowed for `'b`
...
20 | let (left, right) = data.split_at_mut(i);
| ^^^^^^^^^^^^^^^^^^^^ `data` was mutably borrowed here in the previous iteration of the loop
我完全明白不能同时有多个可变引用。但是,我不明白为什么我的代码中有多个。是不是因为我把
&left[j]
存到地图里了?
error[E0502]: cannot borrow `data` as immutable because it is also borrowed as mutable
--> src/main.rs:26:24
|
11 | impl<'b> A<'b> {
| -- lifetime `'b` defined here
12 | pub fn init() -> A<'b> {
13 | let mut data: Vec<AElem<'b>> = Vec::new();
| -------------- type annotation requires that `data` is borrowed for `'b`
...
20 | let (left, right) = data.split_at_mut(i);
| -------------------- mutable borrow occurs here
...
26 | println!("{}", data.len());
| ^^^^^^^^^^ immutable borrow occurs here
为什么此时仍然有对
data
的可变引用?
error[E0505]: cannot move out of `data` because it is borrowed
--> src/main.rs:28:13
|
11 | impl<'b> A<'b> {
| -- lifetime `'b` defined here
12 | pub fn init() -> A<'b> {
13 | let mut data: Vec<AElem<'b>> = Vec::new();
| -------- -------------- type annotation requires that `data` is borrowed for `'b`
| |
| binding `data` declared here
...
20 | let (left, right) = data.split_at_mut(i);
| -------------------- borrow of `data` occurs here
...
28 | A { data }
| ^^^^ move out of `data` occurs here
我根本没有得到这个错误。生命周期说明符可能有问题吗?