首页 > 解决方案 > 如何修复针对 or_insert / or_insert_with 的 clippy::or_fun_call 的 Clippy 警告?

问题描述

我需要计算 Vec 中自定义结构的重复项。我在带有自定义函数的结构的 Vec 中发现计数部分重复

我的代码是:

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,
}

这正是我所需要的。当我使用剪辑时:

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

它给了我接下来两个我无法修复的提示:

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![])`

我尝试更改or_insertor_insert_with,但无法编译。

标签: rustrust-clippy

解决方案


它实际上对我有用的是@user4815162342 答案:

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

推荐阅读