rust - 如何修复针对 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_insert
为or_insert_with
,但无法编译。
解决方案
它实际上对我有用的是@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(())
}
推荐阅读
- swift - 如何在 Xcode 中使用 Apple 的 swift-format?
- vue.js - 为什么 vue 显示 `[Vue warn]: Error in v-on handler: "TypeError: Cannot read property 'content' of undefined"` 错误?
- android - 如何在 Play Billing v3.0 中创建 SkuDetail
- reactjs - 如何在 react.js 中设置输入字段的焦点?
- c++ - QT版本问题
- angular - 角材料表
- .net-core - 什么是并行安装(.NET Core 的主要特征之一)
- android - 如何正确获取传感器管理器的实例或将其替换为 Android NDK 中的等效项?
- javascript - 如何将价格和名称两个数组推入具有键值对的单个数组中
- bash - Bash - 将存储在变量中的文本作为参数时无法识别