Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
671 views
in Technique[技术] by (71.8m points)

rust - Why is the bound `T: 'a` required in order to store a reference `&'a T`?

Given this code:

struct RefWrapper<'a, T> {
    r: &'a T,
}

... the compiler complains:

error: the parameter type T may not live long enough

consider 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:

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is part of the well-formedness rules. The type &'a T is only well-formed if T: 'a (“T outlives 'a”; it is required because we have a reference which we can access during the scope 'a; the pointed-to value in T needs to be valid for at least that scope, too).

struct RefWrapper<'a, T> is a generic type and it says you can input a lifetime 'x and a type U and get a RefWrapper<'x, U> type back. However, this type is not necessarily well-formed or even implemented unless the requirement T: 'a is respected.

This requirement comes from an implementation detail; it's not necessarily so that T and 'a are used together like &'a T in the struct's internals. The well formedness requirement needs to be promoted to the public interface of the RefWrapper struct, so that the requirements of forming a RefWrapper<'_, _> type are public, even if the internal implementation is not.

(There are other places where the same requirement T: 'a comes back but is implict:

pub fn foo<'a, T>(x: &'a T) { }

we spot a difference: here the type &'a T is part of the public api, too.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...