第4章 变量绑定

变量绑定 — Rust By Example

译文 · 基于 Rust By Example

原文链接: https://doc.rust-lang.org/stable/rust-by-example/variable_bindings.html

变量绑定

Rust 通过静态类型确保类型安全。变量绑定可以在声明时说明类型,不过在多数情况下,编译器能够从上下文推导出变量的类型,从而大大减少了类型说明的工作。

使用 let 绑定操作可以将值(比如字面量)绑定(bind)到变量。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
fn main() {
    let an_integer = 1u32;
    let a_boolean = true;
    let unit = ();

    // 将 `an_integer` 复制到 `copied_integer`
    let copied_integer = an_integer;

    println!("An integer: {:?}", copied_integer); // An integer: 1
    println!("A boolean: {:?}", a_boolean); // A boolean: true
    println!("Meet the unit value: {:?}", unit); // Meet the unit value: ()

    // 编译器会对未使用的变量绑定产生警告;可以给变量名加上下划线前缀来消除警告。
    let _unused_variable = 3u32;

    let noisy_unused_variable = 2u32;
    // 改正 ^ 在变量名前加上下划线以消除警告
}

01-可变变量

可变变量 — Rust By Example

02-作用域和遮蔽

作用域和遮蔽 — Rust By Example

03-变量先声明

变量先声明 — Rust By Example

04-冻结

冻结 — Rust By Example

最后修改 October 2, 2026: 更新 (f3447ada6)