我正在嘗試將異步函式作為引數傳遞。異步功能接受一個參考,因為它是爭論的。
use std::future::Future;
async fn f(x: &i32) -> i32 {
todo!()
}
async fn g<F, Fut>(f: F)
where
F: Send Sync 'static for<'a> Fn(&'a i32) -> Fut,
Fut: Future<Output = i32> Send Sync,
{
// let x = 3;
// f(&x).await;
}
#[tokio::main]
async fn main() {
g(f).await;
}
但我有編譯錯誤。
error[E0308]: mismatched types
--> src/main.rs:18:5
|
18 | g(f).await;
| ^ lifetime mismatch
|
= note: expected associated type `<for<'_> fn(&i32) -> impl Future<Output = i32> {f} as FnOnce<(&i32,)>>::Output`
found associated type `<for<'_> fn(&i32) -> impl Future<Output = i32> {f} as FnOnce<(&'a i32,)>>::Output`
= note: the required lifetime does not necessarily outlive the empty lifetime
note: the lifetime requirement is introduced here
--> src/main.rs:9:55
|
9 | F: Send Sync 'static for<'a> Fn(&'a i32) -> Fut,
| ^^^
For more information about this error, try `rustc --explain E0308`.
error: could not compile `test-async-tokio` due to previous error
Fut這里為什么介紹生命周期?如何指定此代碼的生命周期界限?
最好的祝福!
uj5u.com熱心網友回復:
從進一步的測驗來看,似乎我最初的建議是將'a生命周期引數從for<'a>系結到適當泛型引數的 trait 子句中更改,導致編譯器認為生命周期存在于回傳的未來中,從而阻止使用本地變數。即使我明確地將'a生命周期系結到Fut并等待結果,情況似乎也是如此。
我不完全確定為什么您建立的特征邊界不起作用,但我相信這是由于異步函式回傳impl Future而不是已知的具體型別。我遇到了這個問題,與您的原始代碼有一些偏差。這個來源似乎是您問題的解決方案,我在下面為您的特定用例提供了一個修改后的示例。注意:我將f引數重命名為y以強調它不是f直接呼叫函式。
此解決方案添加了一個新的 trait(帶有全面的 impl),可用作F直接系結的 trait ,for<'a>如果輸入/輸出是參考,則需要一個子句。我可能弄錯了,但這似乎是有效的,因為未知的具體未來型別作為關聯型別包含在新特征中,因此g不需要直接擔心它的特征邊界。
use std::future::Future;
trait AsyncFn<T>: Fn(T) -> <Self as AsyncFn<T>>::Fut {
type Fut: Future<Output = <Self as AsyncFn<T>>::Output>;
type Output;
}
impl<T, F, Fut> AsyncFn<T> for F where F: Fn(T) -> Fut, Fut: Future {
type Fut = Fut;
type Output = Fut::Output;
}
async fn f(_: &i32) -> i32 {
todo!()
}
async fn g<F>(y: F) where F: for<'a> AsyncFn<&'a i32, Output = i32> {
let x = 3;
let res = y(&x).await;
}
#[tokio::main]
async fn main() {
g(f).await;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/396759.html
