1

I have an async function which calls another async function which calls another async function... etc.

pub async fn collect_data(&mut self, arg: i32) {
    let futures: Vec<T> = self
        .sections
        .iter_mut()
        .map(|section| section.get_data(arg))
        .collect();
    join!(join_all(futures));
}

The problem is specifying Vec<T>; I don't know what is (and I don't really want to explicitly type it if I can avoid it, since the function arguments might change). I also can't get away with having the compiler infer the types, because it can't figure out that it needs to collect() into a Vec for the join_all(). However, this code does compile:

pub async fn collect_data(&mut self, arg: i32) {
    let mut futures = Vec::new();
    for sect in self.sections.iter_mut() {
        futures.push(sect.get_data(arg));
    }
    join!(join_all(futures));
}

Is there a way to get it to compile with a map instead of creating this mutable vector? Perhaps by specifying just Vec while still having the function infer T from the return value of the map? Or some other way I don't know.

1 Answer 1

3

Yes. To infer a type partially, use _ for the parts you want the compiler to infer:

let futures: Vec<_> = self
    .sections
    .iter_mut()
    .map(|section| section.get_data(arg))
    .collect();
Sign up to request clarification or add additional context in comments.

3 Comments

You can also .collect::<Vec<_>>() if chaining
@MeetTitan Yes (in fact I prefer that style), I just followed the OP's code.
Sick, thanks! I also found out that if I didn't call collect(), that join_all() works on a map object. This is great as well, good tip!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.