rust - 如何在 Rust 中复制而不是借用 i64 到闭包中?
问题描述
我的代码有以下最小示例:
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
只移动/复制一些而不是其他变量?
解决方案
当你在 Rust 中创建一个闭包时,它会通过值或引用来捕获变量。两者的混合是不可能的。默认情况下,它通过引用捕获,但使用move
关键字,它按值捕获(即,它将捕获的变量移动到闭包内)。
因此,在您的第一个代码中,您需要id
在闭包内移动:
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(move |n| (n.clone(), id))
});
}
然后你问你是否可以“内联” ids
:
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)| {
v.iter().map(|n| (n.clone(), ids[i]))
});
}
您根本无法放入ids
内部闭包,因为您已经在FnMut
闭包中(需要独占访问)。因此,您不能借用或移动ids
,因为它已经被FnMut
闭包借用了。最小复制:
fn main() {
let mut i = 0;
let mut closure = || {
i = 2;
|| {
println!("i = {}", i);
}
};
closure()();
}
推荐阅读
- r - 在 R 中使用 tidyverse 如何以固定方式排列列值?
- postgresql - 如何为包含反应式 PostgreSQL 客户端的 Vert.x 服务生成 Rx 化代理?
- algorithm - 如何在相机中心按比例拉长图像
- xml - 如何修改 Odoo 12 网站上的注册表单?
- android - TabLayout.TabView 和 TabLayout.Tab 有什么区别
- apache-spark - Pyspark - 将 RDD 转换为键值对 RDD,键按升序排列
- python - Python关于读取两个txt并输出一个txt的问题
- flutter - 如何在flutter中使用switch语句在sidenavbar上执行signOut?
- python-3.7 - 使用 Python 下载 Sharepoint Online 文件
- oracle - 除了get_ddl过程之外,如何在oracle中获取at表的ddl