【发布时间】:2020-12-30 17:05:46
【问题描述】:
我有一个映射:HashMap<&str, Vec<&str>>,我正在尝试创建一个反向查找映射 HashMap<&str, &str>,它从原始向量中的每个元素指向原始键。
例如如下图
{
"k": vec!["a", "b"]
}
会变成
{
"a": "k",
"b": "k",
}
当我这样做时效果很好:
let substitutes: HashMap<&str, Vec<&str>> = vec![("a", vec!["b", "c"])].into_iter().collect();
// Below works fine
let mut reversed: HashMap<&str, &str> = HashMap::new();
for (&k, v) in substitutes.iter() {
for vv in v.iter() {
reversed.insert(vv, k);
}
}
但是,如果我尝试使用高阶函数来做到这一点,它就不起作用:
// Below doesn't work
let reversed_2: HashMap<&str, &str> = substitutes
.iter()
.flat_map(|(&k, v)| v.iter().map(|&vv| (vv, k)))
.collect();
并给出以下错误:
error[E0373]: closure may outlive the current function, but it borrows `k`, which is owned by the current function
--> src/main.rs:18:42
|
18 | .flat_map(|(&k, v)| v.iter().map(|&vv| (vv, k)))
| ^^^^^ - `k` is borrowed here
| |
| may outlive borrowed value `k`
|
note: closure is returned here
--> src/main.rs:18:29
|
18 | .flat_map(|(&k, v)| v.iter().map(|&vv| (vv, k)))
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: to force the closure to take ownership of `k` (and any other referenced variables), use the `move` keyword
|
18 | .flat_map(|(&k, v)| v.iter().map(move |&vv| (vv, k)))
| ^^^^^^^^^^
error: aborting due to previous error; 1 warning emitted
鉴于k 与flat_map 处于同一范围内,我正试图弄清楚vv 可能比k 寿命更长。
对于获取我的 HOF 方法失败的原因的更多信息将非常有帮助。
【问题讨论】:
标签: rust lifetime higher-order-functions