有时我会遇到生命周期的问题。我还在学习中,不知道这里发生了什么:
use std::future::Future;
use futures::future::{BoxFuture, FutureExt};
struct M{}
struct Client{}
impl Client {
async fn send_and_expect<'a>(
&'a mut self,
m: &M
) -> std::result::Result<(), ()> {
Ok(())
}
pub fn connection_retrier<'a, T>(
f: fn(&'a mut Self, &M) -> T,
f_self: &'a mut Self,
f_m: &'a M,
)-> BoxFuture<'a, std::result::Result<(),()>>
where
T: Future<Output = std::result::Result<(), ()>> + 'a
{
async move {
Client::send_and_expect(f_self, f_m).await
}.boxed()
}
async fn send_with_retry<'a>(&'a mut self) -> std::result::Result<(), ()> {
let m = M{};
Client::connection_retrier(
Client::send_and_expect,
&mut *self, &m).await
}
}
错误:
Compiling playground v0.0.1 (/playground)
error[E0308]: mismatched types
--> src/lib.rs:31:21
|
11 | ) -> std::result::Result<(), ()> {
| --------------------------- the `Output` of this `async fn`'s found opaque type
...
31 | Client::send_and_expect,
| ^^^^^^^^^^^^^^^^^^^^^^^ one type is more general than the other
|
= note: expected fn pointer `for<'r> fn(&mut Client, &'r M) -> impl futures::Future`
found fn pointer `for<'a, '_> fn(&'a mut Client, &M) -> impl futures::Future
对于 for<'r> fn(&mut Client, &'r M) -> impl futures::Future
,为什么&mut Client
没有生命周期,我感到非常困惑。在 for<'a, '_> fn(&'a mut Client, &M) -> impl futures::Future
中,下划线_
的含义是什么?
我非常想了解这里发生了什么。
fn send_and_expect<'a, 'b>(&'a mut self, m: &'b M) -> impl Future<Item=Result<(), ()>> + 'a + 'b
,Result<(), _>
不是一个 future。也许我使用了错误的futures
版本?futures = "0.3.14"
。我不知道如何解决这个错误。你能帮我吗? - boundless-forestasync move {}
包装Ok(())
是有效的。再次感谢。 - boundless-forestfor<'a, '_>
变成了for<'a, 'b>
,那是因为生命周期推断自动为send_and_expect
的签名中第二个引用创建了一个生命周期参数。由于这个参数最初没有名称,编译器将其称为'_
。 - AlphaModdersend_and_expect
是递归的,所以它不能返回一个impl Future
,它必须返回一个BoxFuture
。然而,这给我带来了一个新的错误:https://stackoverflow.com/questions/67239248/recursive-async-function-that-borrows-mutable-variable-twice。你有什么想法吗? - Gatonitopub fn connection_retrier<'a, T>(f: fn(&'a mut Self, &'a Message) -> T,
的概念上卡住了。一开始我以为fn
是一个泛型函数,其参数的生命周期是通用的,但现在我认为它是一个接收具有确切生命周期'a
的参数的函数。然而,在我上面的新问题中,当我调用f
时,我不明白为什么f_self
需要借用'a
。它只需要在f
需要它的时候进行借用即可。然后它可以再次被借用。 - Gatonito