Lifetime complaints depend on whether you attach the value to a variable first #48998
Closed
Description
(Apologies if this is just me misunderstanding Rust, I'm very new to the language.)
Given:
#[derive(Debug)]
struct Foo<'a> {
bar: &'a Bar
}
#[derive(Debug)]
struct Bar {
val: i32
}
fn main() {
let foo = foo_me();
println!("{:?}", foo);
}
The following implementation of foo_me
works:
fn foo_me<'a>() -> Foo<'a> {
Foo {
bar: &Bar {
val: 42
}
}
}
While this one doesn't:
fn foo_me<'a>() -> Foo<'a> {
let bar = Bar {
val: 42
};
Foo {
bar: &bar
}
}
With:
--> src/main.rs:15:15
|
15 | bar: &bar
| ^^^ borrowed value does not live long enough
16 | }
17 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the lifetime 'a as defined on the function body at 10:1...
--> src/main.rs:10:1
|
10 | fn foo_me<'a>() -> Foo<'a> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
I can see what it's complaining about, but I feel like these two examples should function identically. I have a more complicated piece of code that I'm not smart enough to coerce into the working format, so there may be more complicated variants on this which are not solvable.
Activity