]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_error_codes/src/error_codes/E0491.md
Rollup merge of #93556 - dtolnay:trailingcomma, r=cjgillot
[rust.git] / compiler / rustc_error_codes / src / error_codes / E0491.md
1 A reference has a longer lifetime than the data it references.
2
3 Erroneous code example:
4
5 ```compile_fail,E0491
6 struct Foo<'a> {
7     x: fn(&'a i32),
8 }
9
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!
16 }
17 ```
18
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`:
23
24 ```
25 struct Foo<'a> {
26     x: fn(&'a i32),
27 }
28
29 trait Trait<'a, 'b> {
30     type Out;
31 }
32
33 impl<'a, 'b: 'a> Trait<'a, 'b> for usize { // we added the lifetime enforcement
34     type Out = &'a Foo<'b>; // it now works!
35 }
36 ```