问题
Like this code:
use std::future::Future;
use std::pin::Pin;
trait A {
fn handle<'a>(&'a self, data: &'a i32) -> Pin<Box<dyn 'a + Future<Output = ()>>>;
}
impl<'b, Fut> A for fn(&'b i32) -> Fut
where
Fut: 'b + Future<Output = ()>,
{
fn handle<'a>(&'a self, data: &'a i32) -> Pin<Box<dyn 'a + Future<Output = ()>>> {
Box::pin(self(data))
}
}
how can I implement A
for all async fn(&i32)
?
回答1:
This code should works:
use std::future::Future;
use std::pin::Pin;
trait A<'a> {
fn handle(&'a self, data: &'a i32) -> Pin<Box<dyn 'a + Future<Output=()>>>;
}
impl <'a, F, Fut> A<'a> for F
where F: 'static + Fn(&'a i32) -> Fut,
Fut: 'a + Future<Output=()>
{
fn handle(&'a self, data: &'a i32) -> Pin<Box<dyn 'a + Future<Output=()>>> {
Box::pin(self(data))
}
}
then we can use for<'a> A<'a>
to delegate async function everywhere.
async fn processor(data: &i32) {
}
fn consume(a: impl for<'a> A<'a>) {
}
fn main() {
consume(processor);
}
来源:https://stackoverflow.com/questions/60624814/how-to-delegate-an-async-function-with-non-static-parameter-by-a-trait