Rust无法返回引用HashMap get上的局部变量的值
我有一个如下代码:Rust无法返回引用HashMap get上的局部变量的值,rust,rust-cargo,Rust,Rust Cargo,我有一个如下代码: 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();
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");
}
这里是铁锈操场:
有人能提出最低限度解决此问题的替代方案吗?谢谢
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");
}
remove
将值移出映射,并将其作为选项返回
如果您需要一个选项
,您可以在选项
上使用as_ref()
来获得一个。请始终记住,一旦其值超出范围,它就会变得无效。HashMap
hm
是get\u hash\u map()
函数作用域的局部,并在get\u hash\u map()返回时立即删除。hm.get(“1”)
返回的值包含对该HashMap
的引用,因此其生存期也与get\u hash\u map()
的范围相关联,不幸的是,该范围短于所赋予的静态
生存期
如果删除'静态
生存期,并将其替换为函数上的某个'注释
,则会出现类似错误,因为同样没有(合理的)方法从创建该数据所有者的函数返回借用的数据
但是,您可以在周围的作用域中创建映射,并通过对get\u hash\u 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");
}
使用std::collections::HashMap;
fn main(){
让mut hm=HashMap::new();
设x=get_hash_map(&mut hm);
println!(“{:?}”,x);
}
//请注意,返回类型中的'hm'和引用都具有相同的'a life'。
fn获取哈希映射选项您的哈希映射是本地的。它不再存在于函数的末尾。你想做什么?remove()
取消了HashMap
的角色以及OP问题中引用的生存期。如果有另一个代码块/段落涉及到这一点,信息可能会更丰富。@sebpuetz鉴于OP想要做什么还不是非常清楚,remove()
是实现OP想要做的事情的唯一合理方法,而不必完全更改他发布的代码段。我认为这里的引用被误用了,OP可能只是想知道他必须按值返回东西。
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");
}
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");
}