how to learn rust in 7 days
Posted on Sun 17 August 2025 in Journal
Abstract | how to learn rust in 21 days |
---|---|
Authors | Walter Fan |
Category | learning note |
Status | v1.0 |
Updated | 2025-08-17 |
License | CC-BY-NC-ND 4.0 |
“Anyone who stops learning is old, whether at twenty or eighty. Anyone who keeps learning stays young.” —— Henry Ford
"how to learn rust in 7 days"
- "how to learn rust in 7 days"
- 一、Rust 的特点(为什么学 Rust?)
- 二、Rust vs 其他语言速查表
- 三、七天学习计划
- reference
- Daily recitation of 10 English sentences
一、Rust 的特点(为什么学 Rust?)
- 零成本抽象:像 C++ 模板一样高效,但编译器帮你兜底。
- 所有权 & 借用:独特的内存安全模型,无需 GC(Java/Python)或手动释放(C++)。
- 类型系统 & 模式匹配:更强大、更严格,避免运行时错误。
- 并发安全:编译器在编译期就能防止数据竞争。
- 生态:Cargo(包管理 + 构建)、crates.io 丰富库。
- 系统编程能力:能替代 C/C++,但语法更现代。
二、Rust vs 其他语言速查表
特性 | Rust | C++ | Java | Python | Go |
---|---|---|---|---|---|
内存管理 | 所有权/借用,无 GC | 手动 / 智能指针 | GC | GC | GC |
泛型/模板 | 强大,Trait bound | 模板+概念 (C++20) | 泛型 (Java 5+) | 动态类型 | 泛型 (Go 1.18+) |
并发模型 | 线程安全编译期检查 | 线程库 + 锁 | 多线程(锁、并发包) | GIL(限制多核并行) | Goroutines + Channel |
包管理 | Cargo + crates.io | vcpkg/conan 等 | Maven/Gradle | pip, poetry, uv | go mod |
错误处理 | Result<T,E> + ? |
异常 | 异常 | 异常 | error 返回值 |
编译速度 | 较慢 | 中等 | 较快(JIT启动慢) | 快(解释执行) | 很快 |
运行性能 | 接近 C++ | 极高 | 较高(JVM 优化) | 中等(解释/优化有限) | 高(接近 C) |
应用场景 | 系统编程、Web、并发安全 | 系统、游戏、内核 | 企业应用、服务端 | 脚本、数据科学 | 云原生、后端服务 |
三、七天学习计划
第一天:环境与基础
- 目标:安装 Rust,写 Hello World,理解 Cargo。
- 内容:变量、不可变 & 可变、函数、if/loop/match。
- 示例:FizzBuzz。
目标:环境搭建,变量、函数、打印。
fn main() {
// 变量与不可变性
let name = "Rust";
println!("Hello, {}!", name);
// 可变变量
let mut counter = 0;
for i in 1..=5 {
counter += i;
}
println!("Sum of 1..=5 = {}", counter);
// 函数调用
println!("Factorial(5) = {}", factorial(5));
}
fn factorial(n: u32) -> u32 {
if n == 0 { 1 } else { n * factorial(n - 1) }
}
第二天:所有权与借用
- 目标:掌握 Rust 的核心思想:所有权、借用、生命周期。
- 内容:move、clone、&借用、可变借用。
- 示例:统计字符串中不同单词的数量(HashMap)。
fn main() {
let s1 = String::from("ownership");
takes_ownership(s1); // s1 被 move
// println!("{}", s1); // ❌ 会报错
let s2 = String::from("borrowing");
let len = calculate_length(&s2); // 传引用
println!("Length of '{}' is {}", s2, len);
// slice 示例
let word = first_word(&s2);
println!("First word in '{}' is '{}'", s2, word);
}
fn takes_ownership(s: String) {
println!("Got string: {}", s);
}
fn calculate_length(s: &String) -> usize {
s.len()
}
fn first_word(s: &str) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i];
}
}
&s[..]
}
第三天:结构体与枚举
- 目标:学习数据建模方式。
- 内容:
struct
、enum
、impl
方法、Option
/Result
。 - 示例:实现一个简易银行账户(存款/取款)。
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}
enum Shape {
Circle(f64),
Rect(Rectangle),
}
fn main() {
let r = Rectangle { width: 10, height: 20 };
println!("Rectangle {:?}, area = {}", r, r.area());
let c = Shape::Circle(3.0);
let rect = Shape::Rect(r);
match c {
Shape::Circle(radius) => println!("Circle area = {}", std::f64::consts::PI * radius * radius),
Shape::Rect(rec) => println!("Rectangle area = {}", rec.area()),
}
match rect {
Shape::Circle(_) => {}
Shape::Rect(rec) => println!("Matched rect with area {}", rec.area()),
}
}
第四天:模式匹配与错误处理
- 目标:熟练使用
match
、if let
、?
。 - 内容:错误传播、unwrap、expect。
- 示例:实现文件读取,统计文件中每个单词出现的次数。
use std::fs::File;
use std::io::{self, Read};
fn read_file(path: &str) -> io::Result<String> {
let mut f = File::open(path)?; // ? 自动传播错误
let mut contents = String::new();
f.read_to_string(&mut contents)?;
Ok(contents)
}
fn main() {
let filename = "Cargo.toml";
match read_file(filename) {
Ok(text) => println!("Read {}:\n{}", filename, text),
Err(e) => println!("Error reading {}: {}", filename, e),
}
// Option 示例
let numbers = vec![10, 20, 30];
match numbers.get(1) {
Some(v) => println!("Got value {}", v),
None => println!("No value"),
}
}
第五天:泛型与 Trait
- 目标:掌握泛型与 Trait 系统。
- 内容:
impl<T>
、Trait bound、常见 Trait(Display、Debug)。 - 示例:实现一个泛型的二叉搜索树。
use std::fmt::Display;
// 泛型函数
fn largest<T: PartialOrd + Copy>(list: &[T]) -> T {
let mut max = list[0];
for &item in list {
if item > max {
max = item;
}
}
max
}
// Trait 定义与实现
trait Summary {
fn summarize(&self) -> String;
}
struct News {
title: String,
content: String,
}
impl Summary for News {
fn summarize(&self) -> String {
format!("News: {}...", self.title)
}
}
fn notify<T: Summary + Display>(item: &T) {
println!("Breaking: {}", item.summarize());
}
fn main() {
let nums = vec![34, 50, 25, 100, 65];
println!("Largest number = {}", largest(&nums));
let news = News {
title: String::from("Rust 1.80 Released"),
content: String::from("Memory safety and performance improvements..."),
};
println!("{}", news.summarize());
}
第六天:并发与异步
- 目标:体验 Rust 的线程安全与 async。
- 内容:
std::thread
、Arc<Mutex<T>>
、Tokio async。 - 示例:并发下载网页并统计响应大小。
use std::thread;
use std::time::Duration;
use tokio::time;
fn main() {
// 多线程示例
let handles: Vec<_> = (1..=3).map(|i| {
thread::spawn(move || {
println!("Thread {} started", i);
thread::sleep(Duration::from_secs(1));
println!("Thread {} done", i);
})
}).collect();
for h in handles {
h.join().unwrap();
}
// Async 示例(需 tokio runtime)
tokio_main();
}
#[tokio::main]
async fn tokio_main() {
let t1 = task("A");
let t2 = task("B");
tokio::join!(t1, t2);
}
async fn task(name: &str) {
println!("Task {} started", name);
time::sleep(Duration::from_secs(1)).await;
println!("Task {} finished", name);
}
第七天:综合项目
- 目标:将前面知识整合到一个小项目中。
- 内容:CLI 工具,模块化,错误处理,测试。
- 示例:实现一个简易命令行 Todo 应用。
项目结构
todo_app/
├── Cargo.toml
└── src
├── main.rs
├── todo.rs
└── tests.rs
Cargo.toml
[package]
name = "todo_app"
version = "0.1.0"
edition = "2021"
[dependencies]
clap = { version = "4.5", features = ["derive"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
src/todo.rs
use serde::{Serialize, Deserialize};
use std::fs::{self, OpenOptions};
use std::io::{self, Write};
#[derive(Serialize, Deserialize, Debug)]
pub struct Todo {
pub id: usize,
pub task: String,
pub done: bool,
}
const FILE: &str = "todo.json";
pub fn load_todos() -> Vec<Todo> {
let data = fs::read_to_string(FILE).unwrap_or("[]".to_string());
serde_json::from_str(&data).unwrap_or_else(|_| vec![])
}
pub fn save_todos(todos: &Vec<Todo>) -> io::Result<()> {
let data = serde_json::to_string_pretty(todos).unwrap();
let mut file = OpenOptions::new().write(true).create(true).truncate(true).open(FILE)?;
file.write_all(data.as_bytes())
}
pub fn add_task(task: String) -> io::Result<()> {
let mut todos = load_todos();
let id = todos.len() + 1;
todos.push(Todo { id, task, done: false });
save_todos(&todos)
}
pub fn list_tasks() {
let todos = load_todos();
for todo in todos {
println!(
"{}. [{}] {}",
todo.id,
if todo.done { "x" } else { " " },
todo.task
);
}
}
pub fn complete_task(id: usize) -> io::Result<()> {
let mut todos = load_todos();
if let Some(todo) = todos.iter_mut().find(|t| t.id == id) {
todo.done = true;
}
save_todos(&todos)
}
src/main.rs
mod todo;
use clap::{Parser, Subcommand};
#[derive(Parser)]
#[command(name = "todo")]
#[command(about = "A simple CLI Todo app in Rust", long_about = None)]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
/// Add a new todo task
Add { task: String },
/// List all tasks
List,
/// Mark a task as completed
Done { id: usize },
}
fn main() {
let cli = Cli::parse();
match cli.command {
Commands::Add { task } => {
if let Err(e) = todo::add_task(task) {
eprintln!("Error: {}", e);
}
}
Commands::List => {
todo::list_tasks();
}
Commands::Done { id } => {
if let Err(e) = todo::complete_task(id) {
eprintln!("Error: {}", e);
}
}
}
}
src/tests.rs
#[cfg(test)]
mod tests {
use super::super::todo;
#[test]
fn test_add_and_list() {
let _ = todo::add_task("Learn Rust".to_string());
let todos = todo::load_todos();
assert!(todos.iter().any(|t| t.task == "Learn Rust"));
}
#[test]
fn test_complete() {
let _ = todo::add_task("Write tests".to_string());
let todos = todo::load_todos();
let id = todos.last().unwrap().id;
let _ = todo::complete_task(id);
let todos = todo::load_todos();
assert!(todos.iter().find(|t| t.id == id).unwrap().done);
}
}
使用示例
$ cargo run -- add "Learn Rust"
$ cargo run -- add "Build a CLI app"
$ cargo run -- list
1. [ ] Learn Rust
2. [ ] Build a CLI app
$ cargo run -- done 1
$ cargo run -- list
1. [x] Learn Rust
2. [ ] Build a CLI app
reference
Daily recitation of 10 English sentences
- "We need to align our efforts toward a common goal."
-
解释:这句话强调团队合作的重要性。"align our efforts" 意味着让每个人的努力方向一致,确保所有人都朝着同一个目标前进。
-
"Let's take a step back and assess the situation objectively."
-
解释:当你遇到复杂问题时,建议大家暂停下来冷静分析现状。"take a step back" 是一个常用的表达,意思是“退一步看问题”。
-
"This proposal has been thoroughly reviewed by the technical team."
-
解释:在正式汇报前,先确认方案已经经过充分讨论和评估。“thoroughly” 表示“彻底地、全面地”。
-
"I’d like to propose an alternative approach to solve this challenge."
-
解释:提出新思路时,礼貌地使用“propose”这个词,体现尊重他人的态度。“alternative approach” 是“替代方案”的意思。
-
"The timeline seems unrealistic given the current constraints."
-
解释:指出项目计划可能存在不合理之处。"unrealistic" 表示“不现实的”,而 "constraints" 则指“限制条件”。
-
"Can we prioritize tasks based on urgency and impact?"
-
解释:合理安排优先级是高效工作的关键。“urgency” 和 “impact” 是两个重要的考量维度。
-
"We should establish clear communication channels between departments."
-
解释:跨部门协作离不开顺畅的信息传递。“communication channels” 指的就是沟通渠道。
-
"It’s crucial that we document everything clearly for future reference."
-
解释:文档化非常重要,特别是在团队成员变动或后续维护时。“document everything clearly” 强调清晰准确的记录。
-
"What are the potential risks associated with this implementation?"
-
解释:风险评估是项目管理中的重要环节。这个问题可以帮助我们提前识别隐患。
-
"Let’s schedule a follow-up meeting to review the progress next week."
- 解释:定期回顾有助于持续改进。“follow-up meeting” 是“跟进会议”的说法,适合用来安排后续讨论。
本作品采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可。