首页 > 解决方案 > 尽管有足够的信息,但仍需要类型注释

问题描述

我想我会利用 Advent of Code 的机会最终尝试学习 Rust。当我尝试为第 1 天实施解决方案时,我最初尝试过:

use std::io::{self, BufRead};

fn main() {
    let tot = io::stdin().lock().lines()
        .map(|l| l.unwrap())
        .map(|s| s.parse::<i32>().unwrap())
        .map(|i| i / 3 - 2)
        .sum();
    println!("{}", tot);
}

但这失败并出现错误:

error[E0282]: type annotations needed
 --> src/main.rs:4:9
  |
4 |     let tot = io::stdin().lock().lines()
  |         ^^^ consider giving `tot` a type

error: aborting due to previous error

将声明更改为已let tot:i32 = [...]编译并成功。

但是为什么我需要那里的类型注释呢?我只是对i32s的范围求和,那不应该i32默认给我一个吗?

标签: rust

解决方案


推荐阅读