從HashMap或Vec返回引用會(huì)導(dǎo)致借用超出其范圍?我遇到了一個(gè)持續(xù)的編譯錯(cuò)誤,Rust抱怨我在嘗試不斷地借款時(shí)有一個(gè)不可變的借入,但是不變的借入來自另一個(gè)范圍,而且我不會(huì)從它帶來任何東西。我有一些代碼來檢查映射中的值,如果它是存在的,就返回它,否則它需要以各種方式修改映射。問題是,我似乎找不到一種方法讓RUST讓我做這兩種操作,即使這兩個(gè)操作是完全分開的。下面是一些與我的代碼結(jié)構(gòu)相同的荒謬代碼,并展示了問題所在: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}此錯(cuò)誤包括: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這對我來說毫無意義。不可變的借入怎么會(huì)比那個(gè)范圍更長?!其中一個(gè)分支match通過return而另一個(gè)則什么也不做就離開了范圍。我以前見過這種情況,我在其他變量中錯(cuò)誤地將借款從范圍外走私出去,但這里不是這樣的!是的,借用是通過return語句,但這是荒謬的,阻止借入更低的功能-程序不可能返回并繼續(xù)前進(jìn)!如果我在那里返回其他東西,錯(cuò)誤就會(huì)消失,所以我認(rèn)為這就是借閱檢查程序被掛起來的原因。我覺得這就像個(gè)蟲子。不幸的是,我一直無法找到任何方法來重寫它而不會(huì)碰到同樣的錯(cuò)誤,所以如果是這樣的話,這是一個(gè)特別令人討厭的錯(cuò)誤。
從HashMap或Vec返回引用會(huì)導(dǎo)致借用超出其范圍?
森欄
2019-07-09 15:35:16