rofrol
rofrol

Reputation: 15266

Why do I get the error "cannot infer type" when using futures::ok?

I know there is join_all but it cannot infer type:

extern crate futures; // 0.1.25

use futures::future::ok as fut_ok;

fn main() {
    let tasks = vec![fut_ok(1), fut_ok(2), fut_ok(3)];
    println!("{:?}", futures::future::join_all(tasks).wait().unwrap());
}

I got this error:

let tasks = vec![fut_ok(1), fut_ok(2), fut_ok(3)];
    -----        ^^^^^^ cannot infer type for `E`
    |
    consider giving `tasks` a type

Upvotes: 1

Views: 3230

Answers (2)

rofrol
rofrol

Reputation: 15266

Full example

extern crate futures; // 0.1.25
use futures::future::ok as fut_ok;
use futures::future::FutureResult;
fn main() {
    let tasks: Vec<FutureResult<_, ()>> = vec![fut_ok(1), fut_ok(2), fut_ok(3)];
    println!(
        "{:?}",
        futures::future::join_all(tasks).wait().map_err(|_| "Error")
    );
}

Prints Ok([1, 2, 3])

Upvotes: 0

Jmb
Jmb

Reputation: 23359

The problem is that any future may in theory return an error. So the FutureResult type (which is returned from fut_ok) is generic with two type parameters: a type T for success and a type E for errors.

If this was real code instead of a toy example, you would have some error handling code that would allow the compiler to infer type E. In this case you need to specify it, but since you don't use it you can use the empty type (). So either of the following should work:

let tasks: Vec<FutureResult<_, ()>> = vec![fut_ok(1), fut_ok(2), fut_ok(3)];

or

let tasks = vec![fut_ok::<_, ()>(1), fut_ok(2), fut_ok(3)];

Note that the first is what the compiler means when it says: "consider giving tasks a type".

Upvotes: 4

Related Questions