【发布时间】:2021-06-26 12:31:25
【问题描述】:
运行以下代码时,来自attempting the exercise in the 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 变量无法比较。
【问题讨论】:
标签: rust