rust-lang / rust

Empowering everyone to build reliable and efficient software.
https://www.rust-lang.org
Other
96.38k stars 12.45k forks source link

Type inference can't resolve type of output of `dyn Future` inside of `impl Fn` inside of Vec #68064

Open olegnn opened 4 years ago

olegnn commented 4 years ago

This code (Playground)

fn get_closure_vec(length: usize) -> Vec<impl Fn() -> Box<dyn std::future::Future<Output = usize>>> {
    vec![|| Box::new(async { 5 }) as Box<_>; length]
}

gives error

error[E0271]: type mismatch resolving `<impl std::future::Future as std::future::Future>::Output == usize`
 --> src/lib.rs:2:13
  |
2 |     vec![|| Box::new(async { 5 }) as Box<_>; width]
  |             ^^^^^^^^^^^^^^^^^^^^^^^^^^ expected usize, found i32
  |
  = note: required for the cast to the object type `dyn std::future::Future<Output = usize>`

and this code (Playground)

fn get_closure_vec(length: usize) -> Vec<impl Fn() -> Box<dyn std::future::Future<Output = usize>>> {
    vec![|| Box::new(async { 5 }); length]
}

also gives error

error[E0271]: type mismatch resolving `<[closure@src/lib.rs:2:10: 2:39] as std::ops::FnOnce<()>>::Output == std::boxed::Box<(dyn std::future::Future<Output = usize> + 'static)>`
 --> src/lib.rs:1:41
  |
1 | fn get_closure_vec(width: usize) -> Vec<impl Fn() -> Box<dyn std::future::Future<Output = usize>>> {
  |                                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected opaque type, found trait std::future::Future
  |
  = note: expected type `std::boxed::Box<impl std::future::Future>`
             found type `std::boxed::Box<(dyn std::future::Future<Output = usize> + 'static)>`
  = note: the return type of a function must have a statically known size

while this one works fine (Playground)

fn get_closure() -> impl Fn() -> Box<dyn std::future::Future<Output = usize>> {
    || Box::new(async { 5 })
}
Dylan-DPC commented 1 year ago

Update: The first snippet compiles while the second one still fails