0

I'd like to send the async function foo as an argument to the function do_something. The code works fine if foo is not async:

use std::future::Future;

async fn foo(i: i64) -> i64 {
    i * 2
}

async fn do_something<'a, X>(t: &X, x: i64) -> i64
where
    X: Fn(i64) -> dyn Future<Output = i64>,
{
    let x = t(x);
    x.await
}

async fn my_main() {
    println!("{:?}", do_something(&foo, 2).await);
}

The error is:

error[E0277]: the size for values of type `dyn Future<Output = i64>` cannot be known at compilation time
  --> src/lib.rs:11:9
   |
11 |     let x = t(x);
   |         ^ doesn't have a size known at compile-time
   |
   = help: the trait `Sized` is not implemented for `dyn Future<Output = i64>`
   = note: all local variables must have a statically known size
   = help: unsized locals are gated as an unstable feature

error[E0277]: the size for values of type `dyn Future<Output = i64>` cannot be known at compilation time
  --> src/lib.rs:12:5
   |
12 |     x.await
   |     ^^^^^^^ doesn't have a size known at compile-time
   |
   = help: the trait `Sized` is not implemented for `dyn Future<Output = i64>`
   = note: all local variables must have a statically known size
   = help: unsized locals are gated as an unstable feature

error[E0271]: type mismatch resolving `<fn(i64) -> impl Future {foo} as FnOnce<(i64,)>>::Output == (dyn Future<Output = i64> + 'static)`
  --> src/lib.rs:16:22
   |
16 |     println!("{:?}", do_something(&foo, 2).await);
   |                      ^^^^^^^^^^^^ expected trait object `dyn Future`, found opaque type
   |
note: while checking the return type of the `async fn`
  --> src/lib.rs:3:25
   |
3  | async fn foo(i: i64) -> i64 {
   |                         ^^^ checked the `Output` of this `async fn`, found opaque type
   = note: expected trait object `(dyn Future<Output = i64> + 'static)`
               found opaque type `impl Future`
note: required by a bound in `do_something`
  --> src/lib.rs:9:19
   |
7  | async fn do_something<'a, X>(t: &X, x: i64) -> i64
   |          ------------ required by a bound in this
8  | where
9  |     X: Fn(i64) -> dyn Future<Output = i64>,
   |                   ^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `do_something`

What am I'm doing wrong?

Shepmaster
  • 326,504
  • 69
  • 892
  • 1,159
crodas
  • 346
  • 2
  • 8
  • [The duplicate applied](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=9fe9acca002d74fb5fc8b7de9aec4996) – Shepmaster Dec 22 '21 at 03:07

0 Answers0