Rust 不能 return 引用 HashMap 上的局部变量的值获取

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

这里是铁锈游乐场: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");
}

这是无效的,因为您已经声明您将 return 一个 Option<&'static Vec<i32>>,但您 return 一个 Option<&'a Vec<i32>> 其中 'a是当前函数的生命周期。一旦函数 returns,HashMap 将停止存在,释放向量,然后引用将变为悬空。这正是借用检查器旨在避免的情况。

只是 return 值向量:

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 将值移出地图,return将其作为 Option<V>

如果您随后需要 Option<&Vec<i32>>,您只需在 Option<Vec<i32>> 上使用 as_ref() 即可获得。永远记住,一旦它的值超出范围,它就会失效。

HashMap hmget_hash_map() 函数的范围内是局部的,一旦 get_hash_map() return 就被删除。由 hm.get("1") 编辑的值 return 包含对此 HashMap 的引用,因此它的生命周期也与 get_hash_map() 的范围相关,不幸的是,它比归属的 'static 生命周期。

如果你删除 'static 生命周期并用函数上的一些 'a 注释替换它,你会得到类似的错误,因为同样没有(合理的)方法 return 从创建数据所有者的函数中借用数据。

然而,您可以在周围范围内创建地图并通过对 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");
}