![](/img/trans.png)
[英]Programming in Rust , how to fix error[E0515] “cannot return value referencing local variable”?
[英]Rust cannot return value referencing local variable on HashMap get
我的代碼如下所示:
use std::collections::HashMap;
fn main() {
let x = get_hash_map();
println!("{:?}", x);
}
fn get_hash_map() -> Option<&'static Vec<i32>> {
let mut hm = HashMap::new();
let mut vec = Vec::new();
vec.push(1);
hm.insert("1".to_string(), vec);
return hm.get("1");
}
但我得到了這個錯誤:
error[E0515]: cannot return value referencing local variable `hm`
--> src/main.rs:13:12
|
13 | return hm.get("1");
| --^^^^^^^^^
| |
| returns a value referencing data owned by the current function
| `hm` is borrowed here
這是 rust 游樂場: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=7605176aee2dd3ff77a0cfd04a89db55
任何人都可以建議最低限度地解決此問題的替代方案嗎? 謝謝!
fn get_hash_map() -> Option<&'static Vec<i32>> {
let mut hm = HashMap::new();
let mut vec = Vec::new();
vec.push(1);
hm.insert("1".to_string(), vec);
return hm.get("1");
}
這是無效的,因為您已聲明將返回Option<&'static Vec<i32>>
,但您返回的是Option<&'a Vec<i32>>
其中'a
是當前 function 生命周期。 一旦 function 返回,HashMap 將停止存在,釋放向量,然后引用將變得懸空。 這是借用檢查器旨在避免的確切情況。
只需按值返回向量:
fn get_hash_map() -> Option<Vec<i32>> {
let mut hm = HashMap::new();
let mut vec = Vec::new();
vec.push(1);
hm.insert("1".to_string(), vec);
return hm.remove("1");
}
remove
將值移出 map,將其作為Option<V>
返回。
如果你需要一個Option<&Vec<i32>>
,你可以在你的Option<Vec<i32>>
上使用as_ref()
來獲得一個。 永遠記住,一旦它的值超出 scope,它就會失效。
HashMap
hm
位於get_hash_map()
function 的 scope 的本地,並在get_hash_map()
返回后立即刪除。 hm.get("1")
返回的值包含對此HashMap
的引用,因此它的生命周期也與get_hash_map()
的 scope 相關,不幸的是,它比歸屬'static
生命周期”短。
如果您刪除'static
生命周期並用 function 上的一些'a
注釋替換它,您將收到類似的錯誤,因為再次沒有(可靠)方法可以從創建該數據所有者的 function 返回借來的數據。
但是,您可以在周圍的 scope 中創建 map 並通過可變引用將其傳遞給get_hash_map
use std::collections::HashMap;
fn main() {
let mut hm = HashMap::new();
let x = get_hash_map(&mut hm);
println!("{:?}", x);
}
// note that both `hm` and the reference in the return type have the same 'a lifetime.
fn get_hash_map<'a>(hm: &'a mut HashMap<String, Vec<i32>>) -> Option<&'a Vec<i32>> {
let mut vec = Vec::new();
vec.push(1);
hm.insert("1".to_string(), vec);
hm.get("1");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.