Rust 基础语法

变量与可变性、常量、遮蔽、语句与表达式。

Beginner
Key Points变量默认不可变,要改必须 `mut`;`let` 可以重复绑定同一个名字(遮蔽)。

变量默认不可变

Rust
fn main() {
    let x = 5;
    println!("{}", x);

    // x = 6;   // 编译错误:cannot assign twice to immutable variable

    let mut y = 5;
    y = 6;
    println!("{}", y);
}
Output
5
6

Immutability by default is documentation: seeing no mut tells you the value never changes. It also lets the compiler reason about sharing in concurrent code.

常量

Rust
const MAX_POINTS: u32 = 100_000;
static GREETING: &str = "hello";

fn main() {
    println!("{} {}", MAX_POINTS, GREETING);
}
Output
100000 hello
KeywordNeeds typeMutableScope
let否加 mut块
const是永不块(内联展开)
static是需 static mut(不安全)全局

遮蔽(shadowing)

Rust
fn main() {
    let x = 5;
    let x = x + 1;          // 新的 x,遮蔽旧的
    let x = x * 2;
    println!("{}", x);

    // 还能换类型
    let spaces = "   ";
    let spaces = spaces.len();
    println!("{}", spaces);
}
Output
12
3

Shadowing creates a new variable (type may change); mut mutates the same one (type fixed). Shadowing is the natural fit for parse-then-use.

Rust
let input = "  42  ";
let input: i32 = input.trim().parse().unwrap();
println!("{}", input + 1);
Output
43

语句与表达式

Rust
fn main() {
    // 语句:不返回值,以分号结尾
    let y = 6;

    // 表达式:返回值,不加分号
    let z = {
        let a = 3;
        a * 2               // 没有分号 → 这是块的值
    };
    println!("{} {}", y, z);

    let n = if z > 5 { 1 } else { 0 };
    println!("{}", n);
}
Output
6 6
1

**A trailing semicolon turns an expression into a statement returning ()** — the most common beginner error: an extra semicolon at the end of a function yields expected i32, found ().

Rust
fn double(x: i32) -> i32 {
    x * 2          // 对:返回 x*2
}

fn wrong(x: i32) -> i32 {
    x * 2;         // 错:返回 (),类型不匹配
}

Friends & Partners