]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_error_codes/src/error_codes/E0311.md
9477a0b1fb76a7b2128072d98f8d8f4d856f3952
[rust.git] / compiler / rustc_error_codes / src / error_codes / E0311.md
1 This error occurs when there is insufficient information for the rust compiler
2 to prove that some time has a long enough lifetime.
3
4 Erroneous code example:
5
6 ```compile_fail,E0311
7 use std::borrow::BorrowMut;
8
9 trait NestedBorrowMut<U, V> {
10     fn nested_borrow_mut(&mut self) -> &mut V;
11 }
12
13 impl<T, U, V> NestedBorrowMut<U, V> for T
14 where
15     T: BorrowMut<U>,
16     U: BorrowMut<V>, // error: missing lifetime specifier
17 {
18     fn nested_borrow_mut(&mut self) -> &mut V {
19         self.borrow_mut().borrow_mut()
20     }
21 }
22 ```
23
24 In this example we have a trait that borrows some inner data element of type `V`
25 from an outer type `T`, through an intermediate type `U`. The compiler is unable
26 to prove that the livetime of `U` is long enough to support the reference. To
27 fix the issue we can explicitly add lifetime specifiers to the `NestedBorrowMut`
28 trait, which link the lifetimes of the various data types and allow the code to
29 compile.
30
31 Working implementation of the `NestedBorrowMut` trait:
32
33 ```
34 use std::borrow::BorrowMut;
35
36 trait NestedBorrowMut<'a, U, V> {
37     fn nested_borrow_mut(& 'a mut self) -> &'a mut V;
38 }
39
40 impl<'a, T, U, V> NestedBorrowMut<'a, U, V> for T
41 where
42     T: BorrowMut<U>,
43     U: BorrowMut<V> + 'a, // Adding lifetime specifier
44 {
45     fn nested_borrow_mut(&'a mut self) -> &'a mut V {
46         self.borrow_mut().borrow_mut()
47     }
48 }
49 ```