I have two structures, one of which has a type parameter that is set to a reference to another. When I take that reference as an argument in a function, I don't know how to signal that the lifetime should not become dependent.
I've trimmed it down to this example:
use std::marker::PhantomData;
struct Foo<T> {
bar_type: PhantomData<T>,
}
struct Bar {}
impl<T> Foo<T> {
fn takebar(&mut self, bar: T) {}
}
fn main() {
let mut foo: Foo<&Bar> = Foo {
bar_type: PhantomData,
};
let bar = Bar {};
foo.takebar(&bar);
}
This gives me the following compiler error:
error[E0597]: `bar` does not live long enough
--> src/main.rs:19:18
|
19 | foo.takebar(&bar);
| ^^^ borrowed value does not live long enough
20 | }
| - `bar` dropped here while still borrowed
|
= note: values in a scope are dropped in the opposite order they are created
I understand that foo
needs to live as long as bar
here, so I can "resolve" this by declaring bar
before foo
to reverse their destruction order.
This won't work for my situation, and more importantly, I'm not sure why it's happening or how to avoid it. I've tried all sorts of explicit lifetime setups and none of them seem to resolve the problem. If I turn takebar(&mut self, ...
into takebar(&self, ...
, it also works, but I can't always do that. It also works if I move the type parameter to the function from the struct, but again, can't always do that.
How do I communicate that the &bar
reference should not be tied into foo
's lifetime, and only actually needs to live through the function call?