diff --git a/src/lifetime-mismatch.md b/src/lifetime-mismatch.md index ecb6cf20..0bd84b06 100644 --- a/src/lifetime-mismatch.md +++ b/src/lifetime-mismatch.md @@ -71,53 +71,4 @@ blows up in our face! This program is clearly correct according to the reference semantics we actually care about, but the lifetime system is too coarse-grained to handle that. -## Improperly reduced borrows - -The following code fails to compile, because Rust sees that a variable, `map`, -is borrowed twice, and can not infer that the first borrow ceases to be needed -before the second one occurs. This is caused by Rust conservatively falling back -to using a whole scope for the first borrow. This will eventually get fixed. - -```rust,compile_fail -# use std::collections::HashMap; -# use std::hash::Hash; -fn get_default<'m, K, V>(map: &'m mut HashMap, key: K) -> &'m mut V -where - K: Clone + Eq + Hash, - V: Default, -{ - match map.get_mut(&key) { - Some(value) => value, - None => { - map.insert(key.clone(), V::default()); - map.get_mut(&key).unwrap() - } - } -} -``` - -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