首页 > 解决方案 > 带有 .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_countcount变量不能比较。

标签: rust

解决方案


  1. 如果需要显式类型注释,可以使用下一个语义:
for count in mode.keys().collect::<Vec<_>>() {
   // do stuff over each count
}
  1. 您不需要收集项目来循环迭代它们formode.keys()已经是一个迭代器,所以你可以写:
for count in mode.keys() {
    // do stuff
}
  1. 如果您需要从迭代器中获得一些单一结果,最好使用fold
let largest_count = mode.keys().copied().fold(0, |largest, current| largest.max(current));
  1. 在您的特定情况下,您可以只写:
let largets_count = mode.keys().copied().max();

推荐阅读