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

后端 未结 2 1644
情歌与酒
情歌与酒 2020-12-01 15:53

Given this code:

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

... the compiler complains:

error: the param

相关标签:
2条回答
  • 2020-12-01 16:31

    Congratulations, you were right! As of Rust 1.31, thanks to RFC 2093, Infer T: 'x outlives requirements on structs, the requirement on the user to type out this restriction has been removed:

    Remove the need for explicit T: 'x annotations on structs. We will infer their presence based on the fields of the struct. In short, if the struct contains a reference, directly or indirectly, to T with lifetime 'x, then we will infer that T: 'x is a requirement

    Basically, there wasn't a case where this wasn't required, so there wasn't much value in forcing the programmer to write it out.

    0 讨论(0)
  • 2020-12-01 16:32

    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.)

    0 讨论(0)
提交回复
热议问题