3.5 类型推断

05-类型推断 — Comprehensive Rust

译文 · 基于 Comprehensive Rust

原文链接: https://google.github.io/comprehensive-rust/types-and-values/inference.html

3.5 类型推断

Rust 会根据变量的 用法 来确定类型:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
// Copyright 2023 Google LLC
// SPDX-License-Identifier: Apache-2.0
fn takes_u32(x: u32) {
    println!("u32: {x}");
}

fn takes_i8(y: i8) {
    println!("i8: {y}");
}

fn main() {
    let x = 10;
    let y = 20;

    takes_u32(x);
    takes_i8(y);
    // takes_u32(y);
}

本页演示 Rust 编译器如何根据变量声明与用法给出的约束来推断类型。

务必强调:这样声明的变量并不是某种可容纳任意数据的动态“任意类型”。此类声明生成的机器码 与显式声明类型时完全相同。编译器替我们完成工作,帮助我们写出更简洁的代码。

当没有任何约束限制整数字面量的类型时,Rust 默认使用 i32。这有时会在错误信息中显示为 {integer}。类似地,浮点字面量默认使用 f64。

1
2
3
4
5
6
7
8
// Copyright 2023 Google LLC
// SPDX-License-Identifier: Apache-2.0
fn main() {
    let x = 3.14;
    let y = 20;
    assert_eq!(x, y);
    // 错误:没有为 `{float} == {integer}` 实现
}
最后修改 August 11, 2026: 更新 (70a5af133)