rustrust-clippy

How to fix this clippy warning (needless collect)


I have a hard time fixing the needless collect clippy warning.

pub fn import_selection(packages: &mut Vec<PackageRow>) -> io::Result<()> {
    let file = fs::File::open("uad_exported_selection.txt")?;
    let reader = BufReader::new(file);
    let imported_selection: Vec<String> = reader
        .lines()
        .map(|l| l.expect("Could not exported selection"))
        .collect();

    for (i,p) in packages.iter_mut().enumerate() {
        if imported_selection.contains(&p.name) {
            p.selected = true;
            ...
        } else {
            p.selected = false;
        }
    }
    Ok(())
}

I tried to use any() directly from the iterator, it compiles but doesn't seems to work (it doesn't find anything when it should)

Is it really possible to remove the collect in this case?


Solution

  • This is a known issue with current Clippy. It tries to point out that collecting an iterator first and then calling contains(), len(), etc. on the collection is usually unnecessary. Yet current Clippy does not take into account that in your case the result of collect() is used multiple times during the loop, saving you from re-executing the lines().map()-iterator every iteration of that loop.

    It is a false positive.

    You can mark the method or function with #[allow(clippy::needless_collect)] to suppress the lint.