T: 'a 结构体中的推导

Minimum Rust version: nightly

一个注释形式为 T:'a,其中 T 可以是一个类型或另一个生命周期,被称为 “outlives” 要求。 注意 “outlives” 也意味着 'a:'a。

2018版在编写程序时帮助您保持流程的一种方法是,不需要在 struct 定义中明确注释这些 T:'a 的要求。 相反,这些要求将从定义中的字段推断出来。

考虑下面这个 struct 定义,在 Rust 2015 中:

1. // Rust 2015

3. struct Ref<'a, T: 'a> {
4. field: &'a T
5. }

7. // or written with a `where` clause:

9. struct WhereRef<'a, T> where T: 'a {
10. data: &'a T
11. }

13. // with nested references:

15. struct RefRef<'a, 'b: 'a, T: 'b> {
16. field: &'a &'b T,
17. }

19. // using an associated type:

21. struct ItemRef<'a, T: Iterator>
22. where
23. T::Item: 'a
24. {
25. field: &'a T::Item
26. }

在 Rust 2018 中, 这种需求是可以被推导的,你可以这样写:

1. // Rust 2018

3. struct Ref<'a, T> {
4. field: &'a T
5. }

7. struct WhereRef<'a, T> {
8. data: &'a T
9. }

11. struct RefRef<'a, 'b, T> {
12. field: &'a &'b T,
13. }

15. struct ItemRef<'a, T: Iterator> {
16. field: &'a T::Item
17. }

如果您希望在某些情况下更明确,那仍然是可能的。

更多的细节

更多信息,查阅 the tracking issue 和 the RFC.