rust - 带有 .collect() 的 for 循环无法推断类型
问题描述
运行以下代码时,该代码来自尝试 Rust Book 中的练习
代码
use std::collections::HashMap;
fn main() {
let mut values = [5, 34, 31, 4, 31, 25, 28, 45, 43, 14];
values.sort();
let mut total = 0;
let mut mode_collection = HashMap::new();
let mut mode = HashMap::new();
for value in values.iter() {
let count = mode_collection.entry(value.clone()).or_insert(0);
*count += 1;
total += value;
};
for (value, count) in mode_collection.iter() {
let count_values = mode.entry(count).or_insert(vec![]);
count_values.push(value.clone());
}
let mut largest_count: i32 = 0;
for count in mode.keys().collect() {
if count > largest_count {
largest_count = count;
}
}
println!("The average of the values is {}", total / values.len());
println!("The median of the values is {}", values[values.len() / 2]);
println!("The mode of the values is {:?}", mode[&largest_count]);
}
错误
error[E0282]: type annotations needed
--> src\main.rs:24:18
|
24 | for count in mode.keys().collect() {
| ^^^^^^^^^^^^^^^^^^^^^ cannot infer type
error: aborting due to previous error
For more information about this error, try `rustc --explain E0282`.
error: could not compile `enums`
To learn more, run the command again with --verbose.
尝试修复
据我所知,不能将类型注释添加到for
循环中。但是在使用时需要类型注解collect()
。当我摆脱collect()
count
是一个&&{Integer}
(双借整数?)所以largest_count
和count
变量不能比较。
解决方案
- 如果需要显式类型注释,可以使用下一个语义:
for count in mode.keys().collect::<Vec<_>>() {
// do stuff over each count
}
- 您不需要收集项目来循环迭代它们
for
。mode.keys()
已经是一个迭代器,所以你可以写:
for count in mode.keys() {
// do stuff
}
- 如果您需要从迭代器中获得一些单一结果,最好使用
fold
:
let largest_count = mode.keys().copied().fold(0, |largest, current| largest.max(current));
- 在您的特定情况下,您可以只写:
let largets_count = mode.keys().copied().max();
推荐阅读
- r - updateNumericInput not updating from reactiveValues
- c++ - How to replace escaped symbol with its actual value?
- java - 使用java的sql连接的驱动程序问题
- vue.js - How can i make flex-direction column dynamic with vutefyjs classes?
- winapi - Windows API - 在所有显示器上最大化一个窗口
- python - Path.CURVE3 和 Path.CURVE4 有什么问题?贝塞尔曲线在某个点搞砸了
- php - Laravel-8 一对多/多一关系
- laravel-passport - Lighthouse GraphQL - 如何在突变解析器中返回 current_user?
- python - 如何在 Pandas 中定义 4-4-5 周
- excel - 如何切换链接到特定范围的复选框?