How to pass a async function as a parameter to another function?

how to pass a async function as a parameter to another function?

  • i know this question has been asked many times but i could not find a working solution anywhere.

  • although i have implemented this functionality many times before in my projects for some reason i cannot figure it out this time

  • i have tried every variant of the code but nothing is working

//this is what is want to do

struct One{}

struct Two{}

async fn main(){
    //but it does not compile

//cant figer out what this dyn does
async fn giver(One)->dyn Future<Output=Two>{

fn taker(f:F)
where F:Fn(one)->dyn Future<Output=Two>


compiler error

error[E0277]: the size for values of type `(dyn futures::Future<Output = Two> + 'static)` cannot be known at compilation time
  --> apis\billing\src\
41 |   async fn giver(i:One)->dyn Future<Output=Two>{
   |  ______________________________________________^
42 | |     Two {}
43 | |     // future::ready(Two{})
44 | | }
   | |_^ doesn't have a size known at compile-time
   = help: the trait `Sized` is not implemented for `(dyn futures::Future<Output = Two> + 'static)`
   = note: the return type of a function must have a statically known size

things i tried

  • implementing Future for Two
  • Box the function and the output in all combinations
  • BoxFuture the result

i also tried this code

async fn main() {



async fn taker<F,FUT>(f:F)


async fn giver<F>(i:One)->F
    // Two {}

struct One{}

struct Two{}

1 Like

This works:

use std::future::Future;

struct One;
struct Two;

fn main() {

async fn giver(_: One) -> Two {

async fn taker<F>(f: fn(One) -> F)
	F: Future<Output = Two>,
	let two = f(One).await;

you don't mark the return type of an async fn to be Future, the async keyword does that for you.

also, no reason to return a dyn; should only be used if at runtime the values can be of different types


thanks i be so stupid sometimes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.