Given this code:
struct RefWrapper<'a, T> {
r: &'a T,
}
... the compiler complains:
error: the parameter type
T
may not live long enoughconsider adding an explicit lifetime bound
T: 'a
so that the reference type&'a T
does not outlive the data it points at.
I've seen this error multiple times already and so far I just listened to the compiler and everything worked out fine. However, thinking more about it, I don't understand why I have to write T: 'a
.
As far as I understand, it is already impossible to get such a reference. Having &'a T
implies that there is an object of type T
that lives for at least 'a
. But we can't store any references in said object which point to data having a shorter lifetime than 'a
. This would already result in a compiler error.
In that sense it is already impossible to get a &'a T
where T
does not outlive 'a
. Thus the additional annotation (T: 'a
) shouldn't be necessary.
Am I right? Am I wrong and if yes: how could I break code, if T: 'a
would not be required?
Links: