The following code compiles:
trait GenericTrait<T> {}
struct GenericStruct<T> {
func: Box<dyn GenericTrait<T> + 'static>,
}
However, the following doesn't:
trait GenericTrait<T> {}
struct GenericStruct<T> {
func: &'static (dyn GenericTrait<T> + 'static),
}
Instead we get an error:
error[E0310]: the parameter type `T` may not live long enough
--> src/lib.rs:4:11
|
4 | func: &'static (dyn GenericTrait<T> + 'static),
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| |
| the parameter type `T` must be valid for the static lifetime...
| ...so that the reference type `&'static (dyn GenericTrait<T> + 'static)` does not outlive the data it points at
|
help: consider adding an explicit lifetime bound
|
3 | struct GenericStruct<T: 'static> {
| +++++++++
For more information about this error, try `rustc --explain E0310`.
I don't understand why a lifetime bound would be necessary. It is already required that the type implementing GenericTrait<T> has only static lifetimes, why would the type parameter need to be static as well? Even more, why does this work with Box?
This came up in https://discord.com/channels/273534239310479360/1197554265992994846 , but I found this part quite curious.