I just read Niko Matsakis’s blog
Non-lexical Lifetimes: Introduction
I can not understand well the following code, even Niko gives some explain.
I just do not understand well why in the first function, the borrow in the match will last until end of the function.
Can someone give more detail explain?
fn get_default1<'m,K,V:Default>(map: &'m mut HashMap<K,V>,
key: K)
-> &'m mut V {
match map.get_mut(&key) { // -------------+ 'm
Some(value) => return value, // |
None => { } // |
} // |
map.insert(key, V::default()); // |
// ^~~~~~ ERROR (still) |
map.get_mut(&key).unwrap() // |
}
fn get_default2<'m,K,V:Default>(map: &'m mut HashMap<K,V>,
key: K)
-> &'m mut V {
if map.contains(&key) {
// ^~~~~~~~~~~~~~~~~~ 'n
return match map.get_mut(&key) { // + 'm
Some(value) => value, // |
None => unreachable!() // |
}; // v
}
// At this point, `map.get_mut` was never
// called! (As opposed to having been called,
// but its result no longer being in use.)
map.insert(key, V::default()); // OK now.
map.get_mut(&key).unwrap()
}