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

牧云@^-^@ 提交于 2020-03-23 07:55:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!