[英]How do I fix the Clippy warning for clippy::or_fun_call for or_insert / or_insert_with?
I need to count duplicates of a custom struct in a Vec.我需要计算 Vec 中自定义结构的重复项。 I've found count partial duplicates in Vec of structs with a custom function .我在带有自定义函数的结构的 Vec 中发现了count 部分重复项。
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:当我使用 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.我试图将or_insert
更改为or_insert_with
,但它无法编译。
What it actually work for me is @user4815162342 answer:它实际上对我有用的是@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(())
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.