如何延长移交给 tokio spawned co-routine 的变量的生命周期
How to extend lifetime for variable handed over to tokio spawned co-routine
我正在使用 tokio
创建一个新线程以在使用 walkdir 找到的文件路径上执行任务。它基本上如下所示:
pub async fn hash_tree(start_path: &Path) -> std::io::Result<()> {
for entry in WalkDir::new(start_path) {
let file_path_entry = entry.unwrap();
let file_path = file_path_entry.path();
let handle = tokio::spawn(async move {
hashing::hash_file(file_path).await.unwrap();
});
}
此代码的问题是文件路径的寿命不够长。 Rust 失败:
error[E0597]: `file_path_entry` does not live long enough
--> src/main.rs:44:25
|
44 | let file_path = file_path_entry.path();
| ^^^^^^^^^^^^^^^^^^^^^^
| |
| borrowed value does not live long enough
| argument requires that `file_path_entry` is borrowed for `'static`
...
61 | }
| - `file_path_entry` dropped here while still borrowed
我了解这个问题,但不确定如何解决。首先将所有 file_path
聚集在一个向量中,然后将它们推入协同例程会更好吗?我宁愿在发现任务后立即将其启动。我是否可以将 file_path
s 的副本推送到外部范围拥有的向量,以便我可以确保它们存在足够长的时间(编辑:尝试 push
将路径与更大的范围,但也没有用)?
alternative/better 处理该问题的方法是什么?
感谢 Netwave 和 Masklinn!最终起作用的是移动 file_path_entry.clone()
的克隆。正如 Masklinn 指出的那样, path
也是借来的。所以,这有效:
for entry in WalkDir::new(start_path).follow_links(false) {
let file_path_entry = entry.unwrap();
let handle = tokio::spawn(async move {
hashing::hash_file(file_path_entry.clone()).await.unwrap();
});
我正在使用 tokio
创建一个新线程以在使用 walkdir 找到的文件路径上执行任务。它基本上如下所示:
pub async fn hash_tree(start_path: &Path) -> std::io::Result<()> {
for entry in WalkDir::new(start_path) {
let file_path_entry = entry.unwrap();
let file_path = file_path_entry.path();
let handle = tokio::spawn(async move {
hashing::hash_file(file_path).await.unwrap();
});
}
此代码的问题是文件路径的寿命不够长。 Rust 失败:
error[E0597]: `file_path_entry` does not live long enough
--> src/main.rs:44:25
|
44 | let file_path = file_path_entry.path();
| ^^^^^^^^^^^^^^^^^^^^^^
| |
| borrowed value does not live long enough
| argument requires that `file_path_entry` is borrowed for `'static`
...
61 | }
| - `file_path_entry` dropped here while still borrowed
我了解这个问题,但不确定如何解决。首先将所有 file_path
聚集在一个向量中,然后将它们推入协同例程会更好吗?我宁愿在发现任务后立即将其启动。我是否可以将 file_path
s 的副本推送到外部范围拥有的向量,以便我可以确保它们存在足够长的时间(编辑:尝试 push
将路径与更大的范围,但也没有用)?
alternative/better 处理该问题的方法是什么?
感谢 Netwave 和 Masklinn!最终起作用的是移动 file_path_entry.clone()
的克隆。正如 Masklinn 指出的那样, path
也是借来的。所以,这有效:
for entry in WalkDir::new(start_path).follow_links(false) {
let file_path_entry = entry.unwrap();
let handle = tokio::spawn(async move {
hashing::hash_file(file_path_entry.clone()).await.unwrap();
});