How to delegate an async function with non-static parameter by a trait?

382 views Asked by At

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

There are 1 answers

0
Hexilee On BEST ANSWER

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);
}