我有以下代码的最小示例:
现在,当我使用
fn main()
{
let names : Vec<Vec<String>> = vec![
vec!["Foo1".to_string(), "Foo2".to_string()],
vec!["Bar1".to_string(), "Bar2".to_string()]
];
let ids : Vec<i64> = vec![10, 20];
names.iter().enumerate().flat_map(|(i,v)| {
let id : i64 = ids[i];
v.iter().map(|n|
(n.clone(), id)
)
});
}
现在,当我使用
rustc
编译它时,会出现以下错误信息:error[E0597]: `id` does not live long enough
--> main.rs:12:16
|
11 | v.iter().map(|n|
| --- capture occurs here
12 | (n.clone(), id)
| ^^ borrowed value does not live long enough
13 | )
14 | });
| -- borrowed value needs to live until here
| |
| borrowed value only lives until here
但据我了解,id
是 i64
类型,因此应该可以复制到捕获中,这正是我所需要的。
我还尝试过将 id
变量内联,但没有成功:
error[E0597]: `i` does not live long enough
--> main.rs:11:21
|
10 | v.iter().map(|n|
| --- capture occurs here
11 | (n.clone(), ids[i])
| ^ borrowed value does not live long enough
12 | )
13 | });
| -- borrowed value needs to live until here
| |
| borrowed value only lives until here
那么我该如何将我的整数复制到闭包中而不是借用它?
我尝试使用 move
,但 rustc
也不喜欢:
error[E0507]: cannot move out of captured outer variable in an `FnMut` closure
--> main.rs:10:17
|
7 | let ids : Vec<i64> = vec![10, 20];
| --- captured outer variable
...
10 | v.iter().map(move |n|
| ^^^^^^^^ cannot move out of captured outer variable in an `FnMut` closure
所以我需要让rustc
只移动/复制其中一些变量而不是其他变量?
move
。可复制的物品不会被移动,而是被复制。让我找到重复的内容。 - Boiethiosid
时,它不起作用:https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=de2261586d535305991492d18770bbc0 - msrd0