@@ -25,35 +25,30 @@ where
25
25
26
26
Why doesn't this code compile? It helps to look at the lifetime bounds that
27
27
the compiler is automatically adding ("Lifetime Ellision", Chapter 10.3 in the
28
- Rust book) to the ` nested_borrow_mut ` and ` borrow_mut ` functions. In both cases
29
- the input is a reference to ` self ` , so the compiler attempts to assign the
28
+ Rust book) to the ` nested_borrow_mut() ` and ` borrow_mut() ` functions. In both
29
+ cases the input is a reference to ` self ` , so the compiler attempts to assign
30
30
the same lifetime to the input and output.
31
31
32
- Looking specifically at ` nested_borrow_mut ` , we see that there are three object
33
- references to keep track of, along with their associated lifetimes:
32
+ Looking specifically at ` nested_borrow_mut() ` , we see that there are three
33
+ object references to keep track of, along with their associated lifetimes:
34
34
- ` self ` (which is a ` &mut T ` )
35
35
- ` u_ref ` (which is a ` &mut U ` )
36
36
- ` v_ref ` (which is a ` &mut V ` )
37
37
38
38
The ` borrow_mut() ` method implicitly requires that that the input and output
39
- have the same lifetime bounds. Thus the lines:
40
-
41
- ``` rust
42
- let u_ref = self . borrow_mut ();
43
- let v_ref = u_ref . borrow_mut ();
44
- ```
45
-
46
- imply that ` u_ref ` and ` self ` must share a lifetime bound, and also that
47
- ` v_ref ` and ` u_ref ` share a lifetime bound. The problem is that the function
48
- signature for ` nested_borrow_mut ` only gives the compiler information about the
49
- lifetimes of ` self ` and ` v_ref ` -- nothing about ` u_ref ` .
39
+ have the same lifetime bounds. Thus the lines: ` let u_ref = self.borrow_mut(); `
40
+ and ` let v_ref = u_ref.borrow_mut(); ` in ` nested_borrow_mut() ` above imply that
41
+ ` u_ref ` and ` self ` must share a lifetime bound, and also that ` v_ref ` and
42
+ ` u_ref ` share a lifetime bound. The problem is that the function signature for
43
+ ` nested_borrow_mut() ` only gives the compiler information about the lifetimes
44
+ of ` self ` and ` v_ref ` -- nothing about ` u_ref ` .
50
45
51
46
The way to fix this error is then to explicitly tell the compiler that the
52
47
lifetime of ` u_ref ` is the same as ` self ` and ` v_ref ` , which then allows it
53
48
to satisfy the two lifetime bound requirements described above.
54
49
55
50
Here is the working version of the code:
56
- ``` rust
51
+ ```
57
52
use std::borrow::BorrowMut;
58
53
59
54
trait NestedBorrowMut<'a, U, V> {
0 commit comments