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