Appearance
2026-09-19 · 学习笔记 03
Rust 基本语法
变量、函数、分支、循环、结构体五个知识点,每个配最小可运行示例。下一篇《综合示例:稿件检查器》会把这五样拼成一个完整工具。
建个项目跟着敲:
bash
cargo new syntax-demo
cd syntax-demo下面每个知识点是一段代码 + 输出。往 src/main.rs 里敲,cargo run 看输出。
1. 变量
rust
let x = 5; // 不可变变量:声明后不能再改
let mut y = 10; // 可变变量:加了 mut 才能改
y = y + 1;
let price: f64 = 19.9; // 显式标类型:名字: 类型
let name: String = String::from("张道传");
let flag: bool = true;
let letter: char = '中'; // char 是单个字符,单引号
const MIN_CHARS: usize = 2000; // 常量:编译期定死,类型必须显式写rust
println!("x={x} y={y} price={price} name={name} flag={flag} letter={letter}");
println!("达标线 {MIN_CHARS}");输出:
x=5 y=11 price=19.9 name=张道传 flag=true letter=中
达标线 2000要点:
- 默认不可变是 Rust 和 Java 最大的差别。
let x = 5;之后再写x = 6;编译器直接报错。要改值必须写let mut - 类型可省略(编译器从值推断),拿不准就写上
- 字符串是
String,单个字符是char;字符串字面量"中文"的类型是&str(String 的只读视图),这篇先不细分 println!("x={x}")里{x}直接填变量,不用拼加号- 整数类型按位宽和符号命名:
i32(默认)、u32、i64、usize(大小/个数专用)等;小数是f64(默认)和f32
2. 函数
rust
fn add(a: i32, b: i32) -> i32 {
a + b // 没有分号:这一行是表达式,值就是返回值
}
fn word_count(line: &str) -> usize {
line.chars().filter(|c| !c.is_whitespace()).count()
}rust
let sum = add(3, 4);
let w = word_count("中文 abc");
println!("sum={sum} word_count={w}");输出:
sum=7 word_count=5要点:
- 参数和返回值的类型必须显式写(这点和变量相反):
fn 名字(参数: 类型) -> 返回类型 - 不写 return:函数最后一行表达式就是返回值,注意末尾不加分号。加了分号就变成语句,返回
()(空),编译器会报类型不匹配 - 想中途返回才用
return,例如if x < 0 { return 0; } word_count藏着中文字数的坑:"中文 abc".len()是 9(字节数,「中」占 3 字节),chars().count()是 5(字符数)。统计中文必须走chars()|c| !c.is_whitespace()是闭包(匿名小函数),相当于 Java 的c -> !c.isWhitespace()
3. 分支
if——条件不加括号、必须是布尔值:
rust
let count = 1800;
if count >= 2000 {
println!("达标");
} else {
println!("不足");
}if 当表达式用——分支各自返回一个值,直接赋给变量:
rust
let status = if count >= 2000 { "达标" } else { "不足" };match——加强版 switch:
rust
let code = 2;
let msg = match code {
0 => "成功",
1 => "参数错误",
_ => "未知错误", // _ 是兜底,相当于 default
};rust
println!("不足部分:{status}"); // 1800 < 2000
println!("msg={msg}"); // code=2 落到兜底输出:
不足
status=不足
msg=未知错误要点:
if 1 { }编译不过:Rust 不拿数字当布尔,条件必须精确是bool- match 必须覆盖所有情况,漏了编译不过——写
_兜底 - match 同样能当表达式赋值,每一支
=>后面是一个值
4. 循环
rust
for i in 1..=3 { // 1..=3 是闭区间 1,2,3(1..3 是半开区间 1,2)
println!("第{i}遍");
}
let names = ["张三", "李四", "王五"];
for n in names { // 直接遍历数组
println!("人物:{n}");
}
let mut total = 0;
let mut i = 1;
while i <= 100 { // while 和 Java 一样
total += i;
i += 1; // Rust 没有 i++,只有 i += 1
}
println!("1+2+...+100={total}");输出:
第1遍
第2遍
第3遍
人物:张三
人物:李四
人物:王五
1+2+...+100=5050要点:
- 没有 Java 的
for (int i = 0; i < n; i++)三段式,遍历区间和集合都用for x in ... 1..=3含 3,1..3不含 3,就差一个等号- 没有自增自减运算符:
i++不存在,写i += 1 total和i在循环里被修改,都必须let mut
5. 结构体与方法
rust
struct Chapter {
title: String,
char_count: usize,
}
impl Chapter { // impl 块:给结构体挂方法
fn is_passed(&self) -> bool { // &self = Java 的 this
self.char_count >= 2000
}
}rust
let c1 = Chapter {
title: String::from("第1章"),
char_count: 2500,
};
println!("{} {}字 {}", c1.title, c1.char_count, c1.is_passed());输出:
第1章 2500字 true要点:
struct是数据捆扎(相当于 Java 的实体类),没有继承- 方法不写在 struct 里面,写在单独的
impl块里,第一个参数固定是&self - 访问字段和方法都用点:
c1.title、c1.is_passed()——字段不加括号,方法加括号 Chapter { title: ..., char_count: ... }按字段名初始化,一个都不能少
6. 完整可运行版
把上面五段拼起来就是完整 main.rs:
rust
fn main() {
// ===== 1. 变量 =====
let x = 5;
let mut y = 10;
y = y + 1;
let price: f64 = 19.9;
let name: String = String::from("张道传");
let flag: bool = true;
let letter: char = '中';
println!("x={x} y={y} price={price} name={name} flag={flag} letter={letter}");
const MIN_CHARS: usize = 2000;
println!("达标线 {MIN_CHARS}");
// ===== 2. 函数 =====
let sum = add(3, 4);
let w = word_count("中文 abc");
println!("sum={sum} word_count={w}");
// ===== 3. 分支 =====
let count = 1800;
if count >= 2000 {
println!("达标");
} else {
println!("不足");
}
let status = if count >= 2000 { "达标" } else { "不足" };
let code = 2;
let msg = match code {
0 => "成功",
1 => "参数错误",
_ => "未知错误",
};
println!("status={status} msg={msg}");
// ===== 4. 循环 =====
for i in 1..=3 {
println!("第{i}遍");
}
let names = ["张三", "李四", "王五"];
for n in names {
println!("人物:{n}");
}
let mut total = 0;
let mut i = 1;
while i <= 100 {
total += i;
i += 1;
}
println!("1+2+...+100={total}");
// ===== 5. 结构体与方法 =====
let c1 = Chapter {
title: String::from("第1章"),
char_count: 2500,
};
println!("{} {}字 {}", c1.title, c1.char_count, c1.is_passed());
}
fn add(a: i32, b: i32) -> i32 {
a + b
}
fn word_count(line: &str) -> usize {
line.chars().filter(|c| !c.is_whitespace()).count()
}
struct Chapter {
title: String,
char_count: usize,
}
impl Chapter {
fn is_passed(&self) -> bool {
self.char_count >= 2000
}
}7. 对照表
| 知识点 | Rust | Java |
|---|---|---|
| 声明变量 | let x = 5;(默认不可变,改值要 mut) | int x = 5;(随便改) |
| 常量 | const MAX: usize = 2000; | static final int MAX = 2000; |
| 函数 | fn f(a: i32) -> i32 { a + b } | int f(int a) { return a; } |
| if | 条件不加括号,必须是 bool | 条件加括号 |
| switch | match 强制覆盖所有情况 | 忘写 break 会穿透 |
| for | for i in 0..n、for x in list | 三段式 for (int i=0; i<n; i++) |
| 自增 | i += 1 | i++ |
| 实体类 | struct 数据 + impl 方法 | class 数据方法写一起 |
| this | &self | this |
下一篇把这五个知识点拼成一个完整工具:稿件检查器。