我正在尝试迭代向量并将多个异步任务添加到东京计划中,但它抛出错误
inferred to be a FnMut closure
我尝试过克隆数据变量,将其保存在 ARC 和许多其他东西中,但没有任何效果对我有用。
我刚开始学习 Rust,但我仍然不太理解所有概念。
for data in settings.data {
sched.add(
tokio_cron_scheduler::Job::new_async(
data.clone().schedule.as_str(),
move |_, _| Box::pin(async {
println!("{}", data.name);
}),
).unwrap()).await.unwrap();
}
#[derive(Deserialize, Debug)]
pub struct Settings {
pub data: Vec<Data>
}
#[derive(Deserialize, Debug, Clone)]
pub struct Data {
pub name: String,
pub schedule: String
}
这是错误
error: captured variable cannot escape `FnMut` closure body
--> src\main.rs:30:29
|
22 | for data in settings.data {
| ---- variable defined here
...
30 | move |_, _| Box::pin(async {
| ___________________________-_^
| | |
| | inferred to be a `FnMut` closure
31 | | log::info!("starting job for task: {}", &data.name);
| | ---- variable captured here
32 | | }),
| |__________________^ returns a reference to a captured variable which escapes the closure body
|
= note: `FnMut` closures only have access to their captured variables while they are executing...
= note: ...therefore, they cannot allow references to captured variables to escape
我们找到了一个可以使用的解决方案,尽管可以通过许多其他方式完成,但我们尝试在 for 中使用变量。
for data in settings.data {
let shared_data = std::sync::Arc::new(data);
sched.add(
tokio_cron_scheduler::Job::new_async(
shared_data.clone().schedule.as_str(),
move |_, _| {
let data = shared_data.clone();
Box::pin(async move {
println!("{}", data.name);
})
},
).unwrap()).await.unwrap();
}