I ran into a lifetime issue writing some code, and was able to minimize it to the following (Playground):
struct Foo<'a, 'b: 'a, 'c: 'a>(&'a mut &'a (), &'b (), &'c ());
fn with_foo<'b>(_f: impl FnOnce(Foo<'_, 'b, '_>)) {}
struct Bar;
impl Bar {
fn baz<'a>(&'a self, _foo: Foo<'a, '_, '_>) {}
fn call_baz<'b>(&'b self) {
with_foo::<'b>(|foo| self.baz(foo))
}
}
(Edit: you can further simplify by removing 'b
in call_baz()
, it still gives the same error)
Rust gives the following error:
error[E0521]: borrowed data escapes outside of method
--> src/lib.rs:9:30
|
8 | fn call_baz<'b>(&'b self) {
| -- -------- `self` is a reference that is only valid in the method body
| |
| lifetime `'b` defined here
9 | with_foo::<'b>(|foo| self.baz(foo))
| ^^^^^^^^^^^^^
| |
| `self` escapes the method body here
| argument requires that `'b` must outlive `'static`
For more information about this error, try `rustc --explain E0521`.
error: could not compile `playground` (lib) due to 1 previous error
However, editing the definition of Foo
to remove the lifetime bound on 'c
(ie., replacing 'c: 'a
with just 'c
) leads to a successful build. I am struggling to understand why adding the bound 'c: 'a
causes an error?
Edit: a bound of 'c: 'b
also works somehow. Why do 'c
and 'c: 'b
both build successfully, but NOT c: 'a
?