]>
Commit | Line | Data |
---|---|---|
60c5eb7d XL |
1 | A reference has a longer lifetime than the data it references. |
2 | ||
3 | Erroneous code example: | |
4 | ||
5 | ```compile_fail,E0491 | |
dfeec247 XL |
6 | struct Foo<'a> { |
7 | x: fn(&'a i32), | |
60c5eb7d XL |
8 | } |
9 | ||
dfeec247 XL |
10 | trait Trait<'a, 'b> { |
11 | type Out; | |
12 | } | |
13 | ||
14 | impl<'a, 'b> Trait<'a, 'b> for usize { | |
15 | type Out = &'a Foo<'b>; // error! | |
60c5eb7d XL |
16 | } |
17 | ``` | |
18 | ||
dfeec247 XL |
19 | Here, the problem is that the compiler cannot be sure that the `'b` lifetime |
20 | will live longer than `'a`, which should be mandatory in order to be sure that | |
21 | `Trait::Out` will always have a reference pointing to an existing type. So in | |
22 | this case, we just need to tell the compiler than `'b` must outlive `'a`: | |
60c5eb7d XL |
23 | |
24 | ``` | |
dfeec247 XL |
25 | struct Foo<'a> { |
26 | x: fn(&'a i32), | |
27 | } | |
28 | ||
29 | trait Trait<'a, 'b> { | |
30 | type Out; | |
60c5eb7d XL |
31 | } |
32 | ||
dfeec247 XL |
33 | impl<'a, 'b: 'a> Trait<'a, 'b> for usize { // we added the lifetime enforcement |
34 | type Out = &'a Foo<'b>; // it now works! | |
60c5eb7d XL |
35 | } |
36 | ``` |