Rust 入门教程——从零开始的系统编程

Rust 入门教程——从零开始的系统编程

作者: CaoZH
日期: 2026-01-15
本文为原创教程


Rust 连续多年在 Stack Overflow 开发者调查中被评为”最受喜爱的编程语言”。它的内存安全零成本抽象特性,让它在系统编程、WebAssembly、CLI 工具等领域越来越受欢迎。

一、安装 Rust

1
2
3
4
5
6
7
8
9
10
11
12
# 推荐方式:rustup
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

# 验证安装
rustc --version
cargo --version

# 更新
rustup update

# 查看文档(离线)
rustup doc

Hello World

1
2
3
fn main() {
println!("Hello, Rust!");
}
1
2
3
4
5
6
7
8
# 编译运行
rustc hello.rs
./hello

# 或用 cargo
cargo new hello-world
cd hello-world
cargo run

二、基础语法

变量与可变性

1
2
3
4
5
6
7
8
9
10
11
12
13
// 变量默认不可变
let x = 5;
// x = 6; // ❌ 编译错误

// mut 关键字声明可变变量
let mut y = 5;
y = 6; // ✅

// 常量
const MAX_USERS: u32 = 1000;

// 解构赋值
let (a, b) = (1, "hello");

数据类型

1
2
3
4
5
6
7
8
9
10
11
12
// 标量类型
let age: i32 = 28; // 有符号整数
let price: f64 = 99.9; // 浮点数
let done: bool = true; // 布尔值
let letter: char = 'A'; // 字符

// 复合类型
let tup: (i32, f64, &str) = (500, 6.4, "hello");
let (x, y, z) = tup;

let arr: [i32; 3] = [1, 2, 3];
let first = arr[0];

所有权系统

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Rust 的核心特性:所有权规则
// 1. 每个值都有一个所有者
// 2. 同一时间只能有一个所有者
// 3. 所有者离开作用域,值被丢弃

fn main() {
let s1 = String::from("hello");
let s2 = s1; // s1 的所有权转移到 s2
// println!("{}", s1); // ❌ s1 已失效

// 克隆(深拷贝)
let s3 = s2.clone();
println!("{}", s2); // ✅

// 借用(引用)
let len = calculate_length(&s3);
println!("{} 的长度是 {}", s3, len);
}

fn calculate_length(s: &String) -> usize {
s.len() // 不获取所有权
}

函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 函数定义
fn add(x: i32, y: i32) -> i32 {
x + y // 表达式,不带分号即为返回值
}

// 方法
struct Point {
x: f64,
y: f64,
}

impl Point {
fn distance(&self, other: &Point) -> f64 {
let dx = self.x - other.x;
let dy = self.y - other.y;
(dx * dx + dy * dy).sqrt()
}
}

三、实战:CLI 工具

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// src/main.rs
use std::env;
use std::fs;
use std::process;

fn main() {
let args: Vec<String> = env::args().collect();

if args.len() < 2 {
eprintln!("用法: {} <文件路径>", args[0]);
process::exit(1);
}

let file_path = &args[1];

match read_file(file_path) {
Ok(content) => {
let line_count = content.lines().count();
let word_count = content.split_whitespace().count();
let char_count = content.chars().count();

println!("文件: {}", file_path);
println!("行数: {}", line_count);
println!("单词数: {}", word_count);
println!("字符数: {}", char_count);
}
Err(e) => {
eprintln!("读取文件失败: {}", e);
process::exit(1);
}
}
}

fn read_file(path: &str) -> Result<String, std::io::Error> {
fs::read_to_string(path)
}

四、错误处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
use std::fs::File;
use std::io::{self, Read};

// 使用 Result
fn read_username() -> Result<String, io::Error> {
let mut file = File::open("user.txt")?; // ? 运算符传播错误
let mut content = String::new();
file.read_to_string(&mut content)?;
Ok(content.trim().to_string())
}

// 使用 Option
fn find_user(id: i32) -> Option<String> {
let users = vec!["Alice".to_string(), "Bob".to_string()];
users.get(id as usize).cloned()
}

五、常用命令

1
2
3
4
5
6
7
8
9
cargo new project_name     # 创建新项目
cargo build # 编译
cargo build --release # 编译(优化)
cargo run # 编译并运行
cargo check # 检查语法(不生成二进制)
cargo test # 运行测试
cargo doc --open # 生成文档
cargo add serde # 添加依赖
cargo publish # 发布到 crates.io

六、总结

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
## 核心概念
- 所有权(Ownership)
- 借用(Borrowing)
- 生命周期(Lifetime)
- 模式匹配(Pattern Matching)
- 无惧并发(Fearless Concurrency)

## 推荐学习路径
1. ✅ 基础语法 + 所有权
2. ✅ 枚举与模式匹配
3. ✅ 错误处理
4. ✅ 泛型与 trait
5. ✅ 生命周期
6. ✅ 并发编程
7. ✅ unsafe Rust

首发于 CaoZH 的笔记