about summary refs log tree commit diff
path: root/compiler/rustc_error_codes/src/error_codes/E0803.md
blob: 4c022688a2ded7a17cfc584076d45ef252900ee6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
A trait implementation returns a reference without an
explicit lifetime linking it to `self`.
It commonly arises in generic trait implementations
requiring explicit lifetime bounds.

Erroneous code example:

```compile_fail,E0803
trait DataAccess<T> {
    fn get_ref(&self) -> T;
}

struct Container<'a> {
    value: &'a f64,
}

// Attempting to implement reference return
impl<'a> DataAccess<&f64> for Container<'a> {
    fn get_ref(&self) -> &f64 { // Error: Lifetime mismatch
        self.value
    }
}
```

The trait method returns &f64 requiring an independent lifetime
The struct Container<'a> carries lifetime parameter 'a
The compiler cannot verify if the returned reference satisfies 'a constraints
Solution
Explicitly bind lifetimes to clarify constraints:
```
// Modified trait with explicit lifetime binding
trait DataAccess<'a, T> {
    fn get_ref(&'a self) -> T;
}

struct Container<'a> {
    value: &'a f64,
}

// Correct implementation (bound lifetimes)
impl<'a> DataAccess<'a, &'a f64> for Container<'a> {
    fn get_ref(&'a self) -> &'a f64 {
        self.value
    }
}
```