|
| 1 | +This error occurs when there is an unsatisfied outlives bound involving an |
| 2 | +elided region and a generic type parameter or associated type. |
| 3 | + |
| 4 | +Erroneous code example: |
| 5 | + |
| 6 | +```compile_fail,E0311 |
| 7 | +fn no_restriction<T>(x: &()) -> &() { |
| 8 | + with_restriction::<T>(x) |
| 9 | +} |
| 10 | +
|
| 11 | +fn with_restriction<'a, T: 'a>(x: &'a ()) -> &'a () { |
| 12 | + x |
| 13 | +} |
| 14 | +``` |
| 15 | + |
| 16 | +Why doesn't this code compile? It helps to look at the lifetime bounds that are |
| 17 | +automatically added by the compiler. For more details see the documentation for |
| 18 | +[lifetime elision]( https://doc.rust-lang.org/reference/lifetime-elision.html). |
| 19 | + |
| 20 | +The compiler elides the lifetime of `x` and the return type to some arbitrary |
| 21 | +lifetime `'anon` in `no_restriction()`. The only information available to the |
| 22 | +compiler is that `'anon` is valid for the duration of the function. When |
| 23 | +calling `with_restriction()`, the compiler requires the completely unrelated |
| 24 | +type parameter `T` to outlive `'anon` because of the `T: 'a` bound in |
| 25 | +`with_restriction()`. This causes an error because `T` is not required to |
| 26 | +outlive `'anon` in `no_restriction()`. |
| 27 | + |
| 28 | +If `no_restriction()` were to use `&T` instead of `&()` as an argument, the |
| 29 | +compiler would have added an implied bound, causing this to compile. |
| 30 | + |
| 31 | +This error can be resolved by explicitly naming the elided lifetime for `x` and |
| 32 | +then explicily requiring that the generic parameter `T` outlives that lifetime: |
| 33 | + |
| 34 | +``` |
| 35 | +fn no_restriction<'a, T: 'a>(x: &'a ()) -> &'a () { |
| 36 | + with_restriction::<T>(x) |
| 37 | +} |
| 38 | +
|
| 39 | +fn with_restriction<'a, T: 'a>(x: &'a ()) -> &'a () { |
| 40 | + x |
| 41 | +} |
| 42 | +``` |
0 commit comments