Jacob Steinebronn
Jacob Steinebronn

Reputation: 863

Infer inner types while specifying outer type

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.

Upvotes: 1

Views: 88

Answers (1)

Chayim Friedman
Chayim Friedman

Reputation: 70910

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();

Upvotes: 3

Related Questions