Rust 程序设计语言 学习笔记
文档信息
- 来源: https://kaisery.github.io/trpl-zh-cn/
- 类型: 编程语言教程
- 日期: 2026-01-17
- 范围: 第1-5章
核心摘要
《Rust 程序设计语言》是 Rust 官方教程的中文翻译版。本笔记覆盖前五章内容,从环境搭建到核心概念(所有权、结构体)。Rust 是一门注重安全性、并发性和性能的系统编程语言,其独特的所有权系统在编译时就能防止内存错误和数据竞争。
第一章:入门指南
1.1 安装 Rust
核心工具: rustup - Rust 版本管理器
安装命令:
# Linux/macOS
curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh
# Windows: 访问官网下载安装器
常用命令:
rustc --version- 查看版本rustup update- 更新 Rustrustup doc- 本地文档
1.2 Hello, World!
fn main() {
println!("Hello, world!");
}
要点:
fn main()是程序入口println!是宏(带!),不是函数- 语句以分号
;结尾 - Rust 是预编译语言 (AOT)
1.3 Cargo
Cargo 是 Rust 的构建系统和包管理器。
常用命令:
cargo new project_name # 创建项目
cargo build # 编译
cargo run # 编译并运行
cargo check # 快速检查(不生成可执行文件)
cargo build --release # 发布优化编译
项目结构:
project/
├── Cargo.toml # 配置文件
└── src/
└── main.rs # 源代码
第二章:猜数游戏
通过实战项目学习 Rust 基础。
核心概念
| 概念 | 说明 |
|---|---|
let mut |
声明可变变量 |
String::new() |
创建空字符串 |
io::stdin().read_line() |
读取用户输入 |
Result 类型 |
错误处理 |
match 表达式 |
模式匹配 |
| 外部 crate | 使用 rand 生成随机数 |
关键代码片段
use std::io;
use std::cmp::Ordering;
use rand::Rng;
let secret_number = rand::thread_rng().gen_range(1..=100);
let mut guess = String::new();
io::stdin().read_line(&mut guess).expect("读取失败");
let guess: u32 = guess.trim().parse().expect("请输入数字");
match guess.cmp(&secret_number) {
Ordering::Less => println!("太小了"),
Ordering::Greater => println!("太大了"),
Ordering::Equal => println!("正确!"),
}
第三章:常见编程概念
3.1 变量与可变性
默认不可变:
let x = 5; // 不可变
let mut y = 5; // 可变
常量:
const MAX_POINTS: u32 = 100_000; // 必须标注类型
遮蔽 (Shadowing):
let x = 5;
let x = x + 1; // 新变量,可以改变类型
3.2 数据类型
标量类型:
| 类型 | 说明 | 示例 |
|---|---|---|
| 整数 | i8/u8 到 i128/u128 | let a: i32 = 42; |
| 浮点 | f32, f64 (默认) | let b = 3.14; |
| 布尔 | bool | let c = true; |
| 字符 | char (Unicode) | let d = '中'; |
复合类型:
// 元组 - 固定长度,可不同类型
let tup: (i32, f64, u8) = (500, 6.4, 1);
let (x, y, z) = tup; // 解构
let first = tup.0; // 索引访问
// 数组 - 固定长度,相同类型,栈分配
let arr = [1, 2, 3, 4, 5];
let arr = [3; 5]; // [3, 3, 3, 3, 3]
3.3 函数
fn add(x: i32, y: i32) -> i32 {
x + y // 表达式,无分号,作为返回值
}
3.4 控制流
if 表达式:
let number = if condition { 5 } else { 6 };
循环:
// loop - 无限循环
let result = loop {
if done { break value; } // 可返回值
};
// while
while condition { }
// for - 最常用
for element in collection { }
for i in (1..4).rev() { } // 3, 2, 1
第四章:认识所有权
所有权规则(核心)
- 每个值都有一个所有者(变量)
- 同一时刻只能有一个所有者
- 所有者离开作用域时,值被丢弃
移动 vs 克隆
// 移动 (Move) - 堆数据
let s1 = String::from("hello");
let s2 = s1; // s1 失效!
// 克隆 (Clone) - 深拷贝
let s1 = String::from("hello");
let s2 = s1.clone(); // s1 仍有效
// 复制 (Copy) - 栈数据(整数、布尔、浮点、字符、纯Copy元组)
let x = 5;
let y = x; // x 仍有效
引用与借用
// 不可变引用 - 可以有多个
let s = String::from("hello");
let r1 = &s;
let r2 = &s;
// 可变引用 - 同一时刻只能有一个
let mut s = String::from("hello");
let r = &mut s;
借用规则:
- 任意时刻,只能有一个可变引用 或 多个不可变引用
- 引用必须总是有效的(无悬垂引用)
切片
let s = String::from("hello world");
let hello = &s[0..5]; // "hello"
let world = &s[6..11]; // "world"
let slice = &s[..]; // 整个字符串
第五章:使用结构体
定义结构体
struct User {
username: String,
email: String,
active: bool,
sign_in_count: u64,
}
// 实例化
let user = User {
email: String::from("test@example.com"),
username: String::from("test"),
active: true,
sign_in_count: 1,
};
// 字段简写
fn build_user(email: String, username: String) -> User {
User { email, username, active: true, sign_in_count: 1 }
}
// 结构体更新语法
let user2 = User { email: String::from("new@example.com"), ..user };
元组结构体与单元结构体
struct Color(i32, i32, i32); // 元组结构体
struct AlwaysEqual; // 单元结构体
方法与关联函数
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
// 方法 - 第一个参数是 &self
fn area(&self) -> u32 {
self.width * self.height
}
// 关联函数 - 无 self,用 :: 调用
fn square(size: u32) -> Self {
Self { width: size, height: size }
}
}
let rect = Rectangle { width: 30, height: 50 };
let area = rect.area(); // 方法调用
let sq = Rectangle::square(10); // 关联函数调用
知识要点总结
- Rust 是预编译语言,编译后可直接分发
- 变量默认不可变,需
mut才能修改 - 所有权系统是 Rust 内存安全的核心
- 借用规则防止数据竞争
- 模式匹配 (
match) 是处理枚举和错误的利器 - Cargo 是标准的项目管理工具