Here is the code:
#[derive(Debug)]
struct Foo {
f: i32,
}
#[derive(Debug)]
struct Bar<'a> {
bar1: &'a Foo,
bar2: &'a Foo,
}
#[allow(unused_variables)]
fn make_bar<'a>(foo1: &'a Foo, foo2: &'a Foo) -> Bar<'a> {
Bar {
bar1: foo1,
bar2: foo2,
}
}
fn extract_bar2<'a>(foo: &'a Foo) -> &'a Foo {
let foo1 = Foo { f: 22 };
let foo2 = make_bar(&foo, &foo1).bar1;
foo2
}
fn main() {
let foo = Foo { f: 11 };
let foo1 = extract_bar2(&foo);
println!("foo1: {:?}", foo1);
}
This gives an error:
error: `foo1` does not live long enough
--> src/main.rs:23:32
|>
23 |> let foo2 = make_bar(&foo, &foo1).bar1;
|> ^^^^
note: reference must be valid for the lifetime 'a as defined on the block at 21:45...
--> src/main.rs:21:46
|>
21 |> fn extract_bar2<'a>(foo: &'a Foo) -> &'a Foo {
|> ^
note: ...but borrowed value is only valid for the block suffix following statement 0 at 22:29
--> src/main.rs:22:30
|>
22 |> let foo1 = Foo { f: 22 };
|> ^
The core question is: What does a lifetime parameter actually means in the context of a struct?
More specifically: What are the consequences of having the same lifetime parameter for all fields of a struct? Do their lifetimes have to be exactly the same? Do they have to overlap? If so to what extent should they overlap?
What are the (semantic and practical) differences between the following two structs?
struct Bar<'b> {
bar1: &'b Foo,
bar2: &'b Foo,
}
struct Bar<'a, 'b> {
bar1: &'a Foo,
bar2: &'b Foo,
}