Rust executing methods concurrently

Viewed 95

I'm trying to learn rust and have some issues when trying to work with streams of futures. I have the following code

// Stocks: Vec<Stock> || Stock is my struct that implements method get_stock_depth
    let futures = stocks.iter();
    let futures = futures.map(|x| x.get_stock_depth());
    let stream = stream::iter(futures);
    let stream = stream.buffer_unordered(10);

    let result = stream.collect().await;

Stocks vector contains over 800 objects and i figured I'd like to limit concurrent executions. When i'm running the following code i get the following error

type inside async block must be known in this context cannot infer type for type parameter C declared on the associated function collect

Am i missing something?

1 Answers

This almost certainly has nothing to do with async or futures. This is just the normal requirement for collect to provide a type. collect() can create a number of return types and doesn't know what you want. You probably want a Vec like:

let result: Vec<_> = stream.collect().await;

You don't typically need to tell collect what to fill the Vec with (it can usually figure that out), so you can use _, but you do need to tell it what collection type you want.

You might also write this as:

let result = stream.collect::<Vec<_>>().await;

Or if this is the last line of a function that returns result, you can use type inference on the return type by dropping the assignment and the semicolon:

stream.collect().await
Related