Skip to content

Commit 5791ca9

Browse files
authored
Merge pull request #526 from yuzibo/drop-obsolete-section
Remove obsolete improperly reduced borrows example
2 parents 5012a37 + 89cea63 commit 5791ca9

1 file changed

Lines changed: 0 additions & 49 deletions

File tree

src/lifetime-mismatch.md

Lines changed: 0 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -71,53 +71,4 @@ blows up in our face!
7171
This program is clearly correct according to the reference semantics we actually
7272
care about, but the lifetime system is too coarse-grained to handle that.
7373

74-
## Improperly reduced borrows
75-
76-
The following code fails to compile, because Rust sees that a variable, `map`,
77-
is borrowed twice, and can not infer that the first borrow ceases to be needed
78-
before the second one occurs. This is caused by Rust conservatively falling back
79-
to using a whole scope for the first borrow. This will eventually get fixed.
80-
81-
```rust,compile_fail
82-
# use std::collections::HashMap;
83-
# use std::hash::Hash;
84-
fn get_default<'m, K, V>(map: &'m mut HashMap<K, V>, key: K) -> &'m mut V
85-
where
86-
K: Clone + Eq + Hash,
87-
V: Default,
88-
{
89-
match map.get_mut(&key) {
90-
Some(value) => value,
91-
None => {
92-
map.insert(key.clone(), V::default());
93-
map.get_mut(&key).unwrap()
94-
}
95-
}
96-
}
97-
```
98-
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-
12374
[ex2]: lifetimes.html#example-aliasing-a-mutable-reference

0 commit comments

Comments
 (0)