T: 'a inference in structs

Minimum Rust version: 1.31

An annotation in the form of T: 'a, where T is either a type or anotherlifetime, is called an "outlives" requirement. Note that "outlives" alsoimplies 'a: 'a.

One way in which edition 2018 helps you out in maintaining flow when writingprograms is by removing the need to explicitly annotate these T: 'a outlivesrequirements in struct definitions. Instead, the requirements will beinferred from the fields present in the definitions.

Consider the following struct definitions in Rust 2015:

  1. #![allow(unused_variables)]
  2. fn main() {
  3. // Rust 2015
  4. struct Ref<'a, T: 'a> {
  5. field: &'a T
  6. }
  7. // or written with a `where` clause:
  8. struct WhereRef<'a, T> where T: 'a {
  9. data: &'a T
  10. }
  11. // with nested references:
  12. struct RefRef<'a, 'b: 'a, T: 'b> {
  13. field: &'a &'b T,
  14. }
  15. // using an associated type:
  16. struct ItemRef<'a, T: Iterator>
  17. where
  18. T::Item: 'a
  19. {
  20. field: &'a T::Item
  21. }
  22. }

In Rust 2018, since the requirements are inferred, you can instead write:

  1. // Rust 2018
  2. struct Ref<'a, T> {
  3. field: &'a T
  4. }
  5. struct WhereRef<'a, T> {
  6. data: &'a T
  7. }
  8. struct RefRef<'a, 'b, T> {
  9. field: &'a &'b T,
  10. }
  11. struct ItemRef<'a, T: Iterator> {
  12. field: &'a T::Item
  13. }

If you prefer to be more explicit in some cases, that is still possible.

More details

For more details, see the tracking issueand the RFC.