首页 > 解决方案 > Get value out of optional HashMap only when present

问题描述

I have a bit of code that loads a HashMap and then retrieves a value with the map.get(...) method. In my case, it's possible that I may not be able to return a HashMap, so in reality I'm dealing with an Option<HashMap>.

I've managed to isolate my problem in the following snippet:

use std::collections::HashMap;

type MyMap = HashMap<String, String>;

fn get_map() -> Option<MyMap> {
    // In the real case, we may or may not be able to return a map
    Some(MyMap::new())
}

fn main() {
    let res = get_map().and_then(|h| h.get("foo"));
    println!("{:?}", res)
}

I get the following compilation error:

error[E0597]: `h` does not live long enough
  --> src/main.rs:11:38
   |
11 |     let res = get_map().and_then(|h| h.get("foo"));
   |                                      ^          - `h` dropped here while still borrowed
   |                                      |
   |                                      borrowed value does not live long enough
12 |     println!("{:?}", res)
13 | }
   | - borrowed value needs to live until here

(Playground)

I think that I get what's going on here:

There are really two questions here:

  1. Am I understanding this correctly?
  2. How do I fix this?

标签: rust

解决方案


打电话Option::as_ref。它将一个转换Option<T>Option<&T>

use std::collections::HashMap;

type MyMap = HashMap<String, String>;

fn get_map() -> Option<MyMap> {
    // In the real case, we may or may not be able to return a map
    Some(MyMap::new())
}

fn main() {
    let map = get_map();
    let res = map.as_ref().and_then(|h| h.get("foo"));
    println!("{:?}", res)
}

发生的事情是and_then消耗Option; 所以你试图持有对消费数据的引用。

相同的规则适用于 的返回值get_map():如果它没有存储在自己的变量中,它仍然是一个临时值,您不能对其进行引用。


推荐阅读