Rust 基础语法
变量与可变性、常量、遮蔽、语句与表达式。
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
6Immutability 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| Keyword | Needs type | Mutable | Scope |
|---|---|---|---|
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
3Shadowing 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; // 错:返回 (),类型不匹配
}变量默认不可变
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默认不可变不是限制,是文档:读代码时看到没有 mut,就知道这个值不会变。这让并发代码的安全性大大提高——编译器能据此判断共享是否安全。
常量
Rust
const MAX_POINTS: u32 = 100_000;
static GREETING: &str = "hello";
fn main() {
println!("{} {}", MAX_POINTS, GREETING);
}Output
100000 hello| 关键字 | 需标类型 | 可变 | 作用域 |
|---|---|---|---|
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遮蔽和 mut 的区别:遮蔽是新建一个变量(可以换类型),mut 是改同一个变量(类型不变)。所以「解析字符串成数字」时用遮蔽最自然。
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**加分号就变成语句,返回值是 ()**。这是 Rust 新手最常见的错误:函数末尾多写一个分号,编译报 expected i32, found ()。
Rust
fn double(x: i32) -> i32 {
x * 2 // 对:返回 x*2
}
fn wrong(x: i32) -> i32 {
x * 2; // 错:返回 (),类型不匹配
}