簡體   English   中英

Rust - 在閉包中返回未來

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM