Rust newbie here. Can anyone please help me understand why Rust doesn't like this code and how it can be fixed?
struct Foo {
num: u32
}
struct Bar<'a> {
foo: Foo,
num_ref: &'a u32,
}
fn foo<'a>() -> Bar<'a> {
let f = Foo { num: 2 };
let n: &'a u32 = &f.num;
return Bar { foo: f, num_ref: n };
}
fn main() { }
I basically want a function that returns a Bar
, which owns Foo
and a reference to num
(owned by Foo
).
Error:
error[E0597]: `f.num` does not live long enough
--> src/main.rs:12:23
|
12 | let n: &'a u32 = &f.num;
| ^^^^^ borrowed value does not live long enough
13 | return Bar { foo: f, num_ref: n };
14 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the lifetime 'a as defined on the function body at 10:8...
--> src/main.rs:10:8
|
10 | fn foo<'a>() -> Bar<'a> {
| ^^
Thanks in advance!