How do I fix the Clippy warning for clippy::or_fun_call for or_insert / or_insert_with?

550 views Asked by At

I need to count duplicates of a custom struct in a Vec. I've found count partial duplicates in Vec of structs with a custom function.

My code is:

pub fn check_index_duplicates(
    dataset: &[main_index::MotiveImageDefinition],
) -> Result<(), Box<dyn std::error::Error>> {
    let mut keyed = HashMap::new();
    for c in dataset {
        keyed.entry(c.key()).or_insert(vec![]).push(c)
    }

    for (k, v) in &keyed {
        if v.len() > 1 {
            print_an_error(&(format!("Motive {:?} has {} duplicates on index.csv", k, v.len())));
        }
    }
    Ok(())
}

impl main_index::MotiveImageDefinition {
    fn key<'a>(&'a self) -> (&'a str, &'a str) {
        (&self.motive, &self.theme)
    }
}

#[derive(Debug)]
pub struct MotiveImageDefinition {
    pub id: u64,
    pub motive: String,
    pub theme: String,
    pub path: String,
    pub stereo_image: String,
    pub width_pix: String,
    pub height_pix: String,
}

It is exactly what I need. When I use clippy:

cargo clippy --all-targets --all-features -- -D warnings

It gives me the next two hints that I can't fix:

error: use of `or_insert` followed by a function call
   --> src/image/mod.rs:215:30
    |
215 |         keyed.entry(c.key()).or_insert(vec![]).push(c)
    |                              ^^^^^^^^^^^^^^^^^ help: try this: `or_insert_with(vec![])`

I tried to change or_insert to or_insert_with, but it doesn't compile.

1

There are 1 answers

0
user1432966 On

What it actually work for me is @user4815162342 answer:

pub fn check_index_duplicates(
    dataset: &[main_index::MotiveImageDefinition],
) -> Result<(), Box<dyn std::error::Error>> {
    let mut keyed = HashMap::new();
    for c in dataset {
        keyed.entry(c.key()).or_insert_with(Vec::new).push(c)
    }

    for (k, v) in &keyed {
        if v.len() > 1 {
            print_an_error(&(format!("Motive {:?} has {} duplicates on index.csv", k, v.len())));
        }
    }
    Ok(())
}