rust - 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
I think that I get what's going on here:
- The
HashMap
owns all of its key-value pairs. - When I call
h.get(...)
it lends me the value. - Because of that the
HashMap
needs to exist as long as the value exists.
There are really two questions here:
- Am I understanding this correctly?
- How do I fix this?
解决方案
打电话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()
:如果它没有存储在自己的变量中,它仍然是一个临时值,您不能对其进行引用。
推荐阅读
- python - 在 ipython 控制台中调试魔术函数
- visual-studio-2017 - 在 Visual Studio 中将表添加到数据库
- mysql - 在 MySQL 中选择 Random Rows 以与另一个表进行 JOIN
- javascript - 使用媒体查询更改 element.style
- python - Selenium 找不到 javascript 生成的元素
- javascript - 具有可重新排序轴的渐进式渲染平行坐标d3.js V4?
- twitter-bootstrap - Bootstrap 表头组
- elasticsearch - Elasticsearch 别名和索引(相同的 id?)
- powershell - 追加文件的脚本
- javascript - 修改后保留原始数组顺序?