Reputation: 2822
I'm not sure how to properly title this post. I'm fairly new to Rust and trying to compile a program following this simple structure, but it seems to be incorrect, and I'm not sure why.
struct Bar;
impl Bar {
fn do_thing(&self) { println!("Ha, do nothing!") }
}
struct Foo<'a> {
bar: &'a Bar
}
impl<'a> Foo<'a> {
fn new(b: &Bar) -> Foo { Foo { bar: b } }
fn get_bar(&self) -> &Bar { self.bar }
}
fn main() {
let b = Bar;
let b_ref = {
let f = Foo::new(&b);
f.get_bar()
};
b_ref.do_thing();
}
The compiler error here claims that f
does not live long enough. It shouldn't matter how long f
lives though -- b_ref
is valid for as long as b
is, and I thought that references were Copy
so that we wouldn't have to worry about the actual reference in f
. Is this relevant?
Part of me feels like I need to specify the lifetime of the &Bar
being returned from get_bar
, but I don't know how to tie that into the lifetime of the Foo
struct?
What am I missing here?
Upvotes: 0
Views: 539
Reputation: 21505
You have to specify that the reference you are returning is tied to the lifetime 'a
and not the lifetime of self that compiler will infer for you:
impl<'a> Foo<'a> {
fn new(b: &Bar) -> Foo { Foo { bar: b } }
fn get_bar(&self) -> &'a Bar { self.bar }
}
This is equivalent to the original code:
impl<'a> Foo<'a> {
fn new(b: &Bar) -> Foo { Foo { bar: b } }
fn get_bar<'b>(&'b self) -> &'b Bar { self.bar }
}
Part of me feel like I should need to specify the lifetime of the &Bar being returned from get_bar, but I don't know how to tie that into the lifetime of the Foo struct?
The lifetime of Foo
does not matter at all in this case.
Upvotes: 3