Open
Description
In the following code: (playground link)
trait Foo {}
impl<'a> Foo for &'a u32 {}
impl dyn Foo {
fn hello(&self) {}
}
fn convert<'a>(x: &'a &'a u32) {
let y: &dyn Foo = x;
y.hello();
}
The current output is:
error[E0759]: `x` has lifetime `'a` but it needs to satisfy a `'static` lifetime requirement
--> src/lib.rs:8:23
|
7 | fn convert<'a>(x: &'a &'a u32) {
| ----------- this data with lifetime `'a`...
8 | let y: &dyn Foo = x;
| ^ ...is captured here...
9 | y.hello();
| ----- ...and is required to live as long as `'static` here
The error is correct, yet I didn't write 'static
anywhere in the program. What gives? This made me scratch my head for a few minutes. As it turns out, in impl dyn Foo
, dyn Foo
is treated as short for dyn Foo + 'static
. The issue can be fixed by changing impl dyn Foo
to impl<'a> dyn Foo + 'a
.
I wouldn't say the current error is bad, exactly, but it would be nice if rustc could somehow warn the user about what's going on – either by warning on the impl itself, or by somehow attaching an explanation to the type error (though that might not be worth the complexity).