Here is a sample code to verify the behavior of lifetime. I got a compile error.
struct Child<'a> {
name: &'a str,
}
struct Parent<'a> {
child: &'a Child<'a>,
}
impl<'a> Parent<'a> {
fn new(chd: &'a mut Child<'a>) -> Self {
Parent {
child: chd,
}
}
}
fn test(mut chd: Child) {
let _parent = Parent::new(&mut chd);
}
fn main () {
let child: Child = Child{ name: "Jhon" };
test(child);
}
error[E0597]: `chd` does not live long enough
--> test.rs:18:31
|
17 | fn test(mut chd: Child) {
| ------- has type `Child<'1>`
18 | let _parent = Parent::new(&mut chd);
| ------------^^^^^^^^-
| | |
| | borrowed value does not live long enough
| argument requires that `chd` is borrowed for `'1`
19 | }
| - `chd` dropped here while still borrowed
error: aborting due to previous error
For more information about this error, try `rustc --explain E0597`.
I have some resolutions to fix the error, But I don't know why I can fix it.
- Create local value
tmp
and passchd
.
fn test(mut chd: Child) {
let mut tmp = chd;
let _parent = Parent::new(&mut tmp);
}
- Set lifetime to each reference and struct.
struct Parent<'a, 'b> {
child: &'a Child<'b>,
}
impl<'a,'b> Parent<'a,'b> {
fn new(chd: &'a mut Child<'b>) -> Self {
Parent {
child: chd,
}
}
}
- Change
chd
immutable
impl<'a> Parent<'a> {
fn new(chd: &'a Child<'a>) -> Self {
Parent {
child: chd,
}
}
}
fn test(chd: Child) {
let _parent = Parent::new(&chd);
}
IMHO, after Parent::new()
executed, the Child
should be mutable borrowed while the Child
is alive.
And then, the Child
drops at the end of test()
and Child
mutable borrowing also ends. Thus, Child
lived long enough, I think.
So my question is,
- Why does this error happen in spite of
Child
lives long enough? - (if you can) why can I workaround the error by methods 1-3?
Could I hear your opinions, please?
Thanks,