Skip to content

Commit 8565958

Browse files
committed
Adds compile error for example in improperly reduced borrows
1 parent cba5941 commit 8565958

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

src/lifetime-mismatch.md

+24
Original file line numberDiff line numberDiff line change
@@ -96,5 +96,29 @@ where
9696
}
9797
```
9898

99+
Because of the lifetime restrictions imposed, `&mut map`'s lifetime
100+
overlaps other mutable borrows, resulting in a compile error:
101+
102+
```text
103+
error[E0499]: cannot borrow `*map` as mutable more than once at a time
104+
--> src/main.rs:12:13
105+
|
106+
4 | fn get_default<'m, K, V>(map: &'m mut HashMap<K, V>, key: K) -> &'m mut V
107+
| -- lifetime `'m` defined here
108+
...
109+
9 | match map.get_mut(&key) {
110+
| - --- first mutable borrow occurs here
111+
| _____|
112+
| |
113+
10 | | Some(value) => value,
114+
11 | | None => {
115+
12 | | map.insert(key.clone(), V::default());
116+
| | ^^^ second mutable borrow occurs here
117+
13 | | map.get_mut(&key).unwrap()
118+
14 | | }
119+
15 | | }
120+
| |_____- returning this value requires that `*map` is borrowed for `'m`
121+
```
122+
99123

100124
[ex2]: lifetimes.html#example-aliasing-a-mutable-reference

0 commit comments

Comments
 (0)