我正在创建一系列包含对较低级别结构的可变引用的数据结构。我一直在愉快地使用下面的A
、B
和C
,但我尝试添加一个新的层次D
。实际上,A
、B
、C
和D
是协议解码状态机的状态,但我已经在这里删除了所有内容。
struct A {}
fn init_A() -> A {
A {}
}
struct B<'l> {
ed: &'l mut A,
}
fn init_B(mut e: &mut A) -> B {
B { ed: e }
}
struct C<'l> {
pd: &'l mut B<'l>,
}
fn init_C<'l>(mut p: &'l mut B<'l>) -> C<'l> {
C { pd: p }
}
struct D<'lifetime> {
sd: &'lifetime mut C<'lifetime>,
}
fn init_D<'l>(mut p: &'l mut C<'l>) -> D<'l> {
D { sd: p }
}
fn main() {
let mut a = init_A();
let mut b = init_B(&mut a);
let mut c = init_C(&mut b);
// COMMENT OUT THE BELOW LINE FOR SUCCESSFUL COMPILE
let mut d = init_D(&mut c);
}
我遇到了一个错误:
error[E0597]: `c` does not live long enough
--> src/main.rs:38:1
|
37 | let mut d = init_D(&mut c);
| - borrow occurs here
38 | }
| ^ `c` dropped here while still borrowed
|
= note: values in a scope are dropped in the opposite order they are created
我完全不理解在生命周期方面,
D
相对于C
有什么不同:我不明白生命周期不匹配的含义。
init_
函数并不是必要的来统一生命周期。在结构体本身上也可以表现得一样。 - trent