简体   繁体   中英

Rust - return a future in a closure

I am trying to add a return type of a future in a closure. But the compiler is telling me that

`impl Trait` only allowed in function and inherent method return types, not in closure return

I have have also tried wrapping it in Box but that didn't work. I tried type aliases but they are nighly only features. I am unable to understand how else can I solve it.

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: I want to wrap the closure output in an Result type and hence a return type is necessary.

Don't annotate the future.

If you need to annotate the enclosing type (eg Result ), you can either annotate it when returning it ( Result::<_, ErrorType> ) or as the return type, but let inference find the future type itself with _ : || -> Result<_, ErrorType> || -> Result<_, ErrorType> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM