[英]Rust - return a future in a closure
我正在尝试在闭包中添加未来的返回类型。 但是编译器告诉我
`impl Trait` only allowed in function and inherent method return types, not in closure return
我也尝试过将它包装在Box
中,但没有奏效。 我尝试了type aliases
,但它们几乎是唯一的功能。 我无法理解我还能如何解决它。
pub async fn execute_event_handler(
event_handler: Option<Arc<PyFunction>>,
event_loop: Arc<Py<PyAny>>,
) -> Result<(), Box<dyn std::error::Error>> {
if let Some(handler) = event_handler {
match &(*handler) {
PyFunction::SyncFunction(function) => {
println!("Startup event handler");
Python::with_gil(|py| -> Result<(), Box<dyn std::error::Error>> {
function.call0(py)?;
Ok(())
})?;
}
PyFunction::CoRoutine(function) => {
let future = Python::with_gil(
|py| -> impl Future<Output = Result<Py<PyAny>, PyErr>> + Send { // this is giving an error
println!("Startup event handler async");
let coroutine = function.as_ref(py).call0().unwrap();
pyo3_asyncio::into_future_with_loop((*event_loop).as_ref(py), coroutine)
.unwrap()
},
);
future.await?;
}
}
}
Ok(())
}
PS:我想将闭包输出包装在Result
类型中,因此需要返回类型。
不要注释未来。
如果您需要注释封闭类型(例如Result
),您可以在返回时对其进行注释( Result::<_, ErrorType>
)或作为返回类型,但让推理使用_
找到未来类型本身: || -> Result<_, ErrorType>
|| -> Result<_, ErrorType>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.