From cba5941207a16bdc3b003438b8046da85b87eab6 Mon Sep 17 00:00:00 2001 From: Milan Date: Mon, 18 Jan 2021 11:29:33 -0500 Subject: [PATCH 1/2] Changes wording under improperly reduced borrows --- src/lifetime-mismatch.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lifetime-mismatch.md b/src/lifetime-mismatch.md index d96240e..e44d99f 100644 --- a/src/lifetime-mismatch.md +++ b/src/lifetime-mismatch.md @@ -74,7 +74,7 @@ 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. From 856595872a68c7b022efaafe419aab4bdb6aaa0e Mon Sep 17 00:00:00 2001 From: Milan Date: Mon, 18 Jan 2021 11:30:05 -0500 Subject: [PATCH 2/2] Adds compile error for example in improperly reduced borrows --- src/lifetime-mismatch.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/lifetime-mismatch.md b/src/lifetime-mismatch.md index e44d99f..c53648c 100644 --- a/src/lifetime-mismatch.md +++ b/src/lifetime-mismatch.md @@ -96,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, 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