diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-17 12:11:38 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-17 12:13:23 +0000 |
commit | 20431706a863f92cb37dc512fef6e48d192aaf2c (patch) | |
tree | 2867f13f5fd5437ba628c67d7f87309ccadcd286 /compiler/rustc_error_codes/src/error_codes/E0311.md | |
parent | Releasing progress-linux version 1.65.0+dfsg1-2~progress7.99u1. (diff) | |
download | rustc-20431706a863f92cb37dc512fef6e48d192aaf2c.tar.xz rustc-20431706a863f92cb37dc512fef6e48d192aaf2c.zip |
Merging upstream version 1.66.0+dfsg1.
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'compiler/rustc_error_codes/src/error_codes/E0311.md')
-rw-r--r-- | compiler/rustc_error_codes/src/error_codes/E0311.md | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/compiler/rustc_error_codes/src/error_codes/E0311.md b/compiler/rustc_error_codes/src/error_codes/E0311.md new file mode 100644 index 000000000..08159d3f4 --- /dev/null +++ b/compiler/rustc_error_codes/src/error_codes/E0311.md @@ -0,0 +1,42 @@ +This error occurs when there is an unsatisfied outlives bound involving an +elided region and a generic type parameter or associated type. + +Erroneous code example: + +```compile_fail,E0311 +fn no_restriction<T>(x: &()) -> &() { + with_restriction::<T>(x) +} + +fn with_restriction<'a, T: 'a>(x: &'a ()) -> &'a () { + x +} +``` + +Why doesn't this code compile? It helps to look at the lifetime bounds that are +automatically added by the compiler. For more details see the documentation for +[lifetime elision]( https://doc.rust-lang.org/reference/lifetime-elision.html). + +The compiler elides the lifetime of `x` and the return type to some arbitrary +lifetime `'anon` in `no_restriction()`. The only information available to the +compiler is that `'anon` is valid for the duration of the function. When +calling `with_restriction()`, the compiler requires the completely unrelated +type parameter `T` to outlive `'anon` because of the `T: 'a` bound in +`with_restriction()`. This causes an error because `T` is not required to +outlive `'anon` in `no_restriction()`. + +If `no_restriction()` were to use `&T` instead of `&()` as an argument, the +compiler would have added an implied bound, causing this to compile. + +This error can be resolved by explicitly naming the elided lifetime for `x` and +then explicily requiring that the generic parameter `T` outlives that lifetime: + +``` +fn no_restriction<'a, T: 'a>(x: &'a ()) -> &'a () { + with_restriction::<T>(x) +} + +fn with_restriction<'a, T: 'a>(x: &'a ()) -> &'a () { + x +} +``` |