|
1 | | -#### Note: this error code is no longer emitted by the compiler. |
| 1 | +A trait implementation returns a reference without an explicit lifetime linking it to `self`. |
2 | 2 |
|
3 | | -A lifetime cannot be determined in the given situation. |
| 3 | +```compile_fail,E0495 |
| 4 | +trait Tr<X> { |
| 5 | + fn f(&self) -> X; |
| 6 | +} |
4 | 7 |
|
5 | | -Erroneous code example: |
| 8 | +struct Wr<'b> { |
| 9 | + ri: &'b i32, |
| 10 | + f: f32, |
| 11 | +} |
6 | 12 |
|
7 | | -```compile_fail |
8 | | -fn transmute_lifetime<'a, 'b, T>(t: &'a (T,)) -> &'b T { |
9 | | - match (&t,) { // error! |
10 | | - ((u,),) => u, |
| 13 | +impl<'b> Tr<&f32> for Wr<'b> { |
| 14 | + fn f(&self) -> &f32 { // error: missing lifetime linking &f32 to self |
| 15 | + &self.f |
11 | 16 | } |
12 | 17 | } |
13 | | -
|
14 | | -let y = Box::new((42,)); |
15 | | -let x = transmute_lifetime(&y); |
16 | 18 | ``` |
| 19 | +Specify an explicit lifetime in the trait to ensure that the reference returned is valid for at least as long as `self`: |
17 | 20 |
|
18 | | -In this code, you have two ways to solve this issue: |
19 | | - 1. Enforce that `'a` lives at least as long as `'b`. |
20 | | - 2. Use the same lifetime requirement for both input and output values. |
21 | | - |
22 | | -So for the first solution, you can do it by replacing `'a` with `'a: 'b`: |
23 | | - |
24 | | -``` |
25 | | -fn transmute_lifetime<'a: 'b, 'b, T>(t: &'a (T,)) -> &'b T { |
26 | | - match (&t,) { // ok! |
27 | | - ((u,),) => u, |
28 | | - } |
| 21 | +```rust |
| 22 | +trait Tr<'a, X> { |
| 23 | + fn f(&'a self) -> X; |
29 | 24 | } |
30 | | -``` |
31 | 25 |
|
32 | | -In the second you can do it by simply removing `'b` so they both use `'a`: |
| 26 | +struct Wr<'b> { |
| 27 | + ri: &'b i32, |
| 28 | + f: f32, |
| 29 | +} |
33 | 30 |
|
34 | | -``` |
35 | | -fn transmute_lifetime<'a, T>(t: &'a (T,)) -> &'a T { |
36 | | - match (&t,) { // ok! |
37 | | - ((u,),) => u, |
| 31 | +impl<'a, 'b: 'a> Tr<'a, &'a f32> for Wr<'b> { |
| 32 | + fn f(&'a self) -> &'a f32 { // ok! |
| 33 | + &self.f |
38 | 34 | } |
39 | 35 | } |
40 | 36 | ``` |
0 commit comments