Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading