![](/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.