|
| 1 | +A lifetime parameter of a function definition is called *late-bound* if it both: |
| 2 | + |
| 3 | +1. appears in an argument type |
| 4 | +2. does not appear in a generic type constraint |
| 5 | + |
| 6 | +You cannot specify lifetime arguments for late-bound lifetime parameters. |
| 7 | + |
| 8 | +Erroneous code example: |
| 9 | + |
| 10 | +```compile_fail,E0794 |
| 11 | +fn foo<'a>(x: &'a str) -> &'a str { x } |
| 12 | +let _ = foo::<'static>; |
| 13 | +``` |
| 14 | + |
| 15 | +The type of a concrete instance of a generic function is universally quantified |
| 16 | +over late-bound lifetime parameters. This is because we want the function to |
| 17 | +work for any lifetime substituted for the late-bound lifetime parameter, no |
| 18 | +matter where the function is called. Consequently, it doesn't make sense to |
| 19 | +specify arguments for late-bound lifetime parameters, since they are not |
| 20 | +resolved until the function's call site(s). |
| 21 | + |
| 22 | +To fix the issue, remove the specified lifetime: |
| 23 | + |
| 24 | +``` |
| 25 | +fn foo<'a>(x: &'a str) -> &'a str { x } |
| 26 | +let _ = foo; |
| 27 | +``` |
| 28 | + |
| 29 | +### Additional information |
| 30 | + |
| 31 | +Lifetime parameters that are not late-bound are called *early-bound*. |
| 32 | +Confusion may arise from the fact that late-bound and early-bound |
| 33 | +lifetime parameters are declared the same way in function definitions. |
| 34 | +When referring to a function pointer type, universal quantification over |
| 35 | +late-bound lifetime parameters can be made explicit: |
| 36 | + |
| 37 | +``` |
| 38 | +trait BarTrait<'a> {} |
| 39 | + |
| 40 | +struct Bar<'a> { |
| 41 | + s: &'a str |
| 42 | +} |
| 43 | + |
| 44 | +impl<'a> BarTrait<'a> for Bar<'a> {} |
| 45 | + |
| 46 | +fn bar<'a, 'b, T>(x: &'a str, _t: T) -> &'a str |
| 47 | +where T: BarTrait<'b> |
| 48 | +{ |
| 49 | + x |
| 50 | +} |
| 51 | + |
| 52 | +let bar_fn: for<'a> fn(&'a str, Bar<'static>) -> &'a str = bar; // OK |
| 53 | +let bar_fn2 = bar::<'static, Bar>; // Not allowed |
| 54 | +let bar_fn3 = bar::<Bar>; // OK |
| 55 | +``` |
| 56 | + |
| 57 | +In the definition of `bar`, the lifetime parameter `'a` is late-bound, while |
| 58 | +`'b` is early-bound. This is reflected in the type annotation for `bar_fn`, |
| 59 | +where `'a` is universally quantified and `'b` is substituted by a specific |
| 60 | +lifetime. It is not allowed to explicitly specify early-bound lifetime |
| 61 | +arguments when late-bound lifetime parameters are present (as for `bar_fn2`, |
| 62 | +see issue #42868: https://github.com/rust-lang/rust/issues/42868), although the |
| 63 | +types that are constrained by early-bound parameters can be specified (as for |
| 64 | +`bar_fn3`). |
0 commit comments