]> git.proxmox.com Git - rustc.git/blobdiff - src/doc/nomicon/src/lifetime-mismatch.md
New upstream version 1.52.0~beta.3+dfsg1
[rustc.git] / src / doc / nomicon / src / lifetime-mismatch.md
index 5d7500dd9968679ae8a365e2134cbbbd8f9fd269..c53648c53f2c4d108677592661c1fe7e0f574932 100644 (file)
@@ -74,13 +74,12 @@ care about, but the lifetime system is too coarse-grained to handle that.
 
 # Improperly reduced borrows
 
-This currently fails to compile, because Rust doesn't understand that the borrow
+The following code fails to compile, because Rust doesn't understand that the borrow
 is no longer needed and conservatively falls back to using a whole scope for it.
 This will eventually get fixed.
 
 ```rust,edition2018,compile_fail
 # use std::collections::HashMap;
-# use std::cmp::Eq;
 # use std::hash::Hash;
 fn get_default<'m, K, V>(map: &'m mut HashMap<K, V>, key: K) -> &'m mut V
 where
@@ -97,5 +96,29 @@ where
 }
 ```
 
+Because of the lifetime restrictions imposed, `&mut map`'s lifetime
+overlaps other mutable borrows, resulting in a compile error:
+
+```text
+error[E0499]: cannot borrow `*map` as mutable more than once at a time
+  --> src/main.rs:12:13
+   |
+4  |   fn get_default<'m, K, V>(map: &'m mut HashMap<K, V>, key: K) -> &'m mut V
+   |                  -- lifetime `'m` defined here
+...
+9  |       match map.get_mut(&key) {
+   |       -     --- first mutable borrow occurs here
+   |  _____|
+   | |
+10 | |         Some(value) => value,
+11 | |         None => {
+12 | |             map.insert(key.clone(), V::default());
+   | |             ^^^ second mutable borrow occurs here
+13 | |             map.get_mut(&key).unwrap()
+14 | |         }
+15 | |     }
+   | |_____- returning this value requires that `*map` is borrowed for `'m`
+```
+
 
 [ex2]: lifetimes.html#example-aliasing-a-mutable-reference