如何编写返回impl Future的函数指针签名?


我正在尝试设计一个函数send_with_retry,它发送一条消息,然后在连接关闭时重试。错误和结果放在这里并不是为了让它变得非常简单,但在真实的示例中,它会观察返回值,以便知道连接何时关闭或成功。

struct Client {
    
}

impl Client {
    async fn send_and_expect(
        &mut self
    ) -> std::result::Result<(), ()> {
        Ok(())
    }
    
    pub fn connection_retrier(
        f: fn(&mut Self) -> std::result::Result<(), ()>,
        f_self: &mut Self,
    ) -> std::result::Result<(), ()> {
        Ok(())
    }
    
    fn send_with_retry(&mut self) -> std::result::Result<(), ()> {
           Client::connection_retrier(Client::send_and_expect, &mut self)
    }
}

但是我得到了这个错误:

Error:
   Compiling playground v0.0.1 (/playground)
error[E0308]: mismatched types
  --> src/lib.rs:20:39
   |
20 |            Client::connection_retrier(Client::send_and_expect, &mut self)
   |                                       ^^^^^^^^^^^^^^^^^^^^^^^ expected enum `std::result::Result`, found opaque type
   |
   = note: expected fn pointer `for<'r> fn(&'r mut Client) -> std::result::Result<(), ()>`
                 found fn item `for<'_> fn(&mut Client) -> impl Future {Client::send_and_expect}`

error: aborting due to previous error

当然,问题在于,因为我指定了一个返回Result的函数poiter f,但是我传递了一个指向async函数的指针,该函数对返回impl Future的函数进行去丑化。

应该放在f参数中的正确函数签名是什么?

转载请注明出处:http://www.souyuntu.com/article/20230526/2297756.html