从HashMap或Vec返回引用会导致借用超出其范围?
use std::collections::BTreeMap;fn do_stuff(map: &mut BTreeMap<i32, i32>, key: i32) -> Option<&i32> { // extra scope in vain attempt to contain the borrow { // borrow immutably if let Some(key) = map.get(&key) { return Some(key); } } // now I'm DONE with the immutable borrow, but rustc still thinks it's borrowed map.insert(0, 0); // borrow mutably, which errors None}
error[E0502]: cannot borrow `*map` as mutable because it is also borrowed as immutable --> src/lib.rs:14:5 | 3 | fn do_stuff(map: &mut BTreeMap<i32, i32>, key: i32) -> Option<&i32> { | - let's call the lifetime of this reference `'1` ... 7 | if let Some(key) = map.get(&key) { | --- immutable borrow occurs here 8 | return Some(key); | --------- returning this value requires that `*map` is borrowed for `'1` ... 14 | map.insert(0, 0); // borrow mutably, which errors | ^^^^^^^^^^^^^^^^ mutable borrow occurs here
match
return
return
守着一只汪