恭喜你走到最后一课!🎉 本课将综合前面所学的所有知识,构建一个全栈Rust应用。从CLI工具到Web服务,从数据库到WASM前端,体验Rust的全栈开发能力。
// 全栈Rust应用架构:
//
// todo-app/
// ├── Cargo.toml (workspace)
// ├── crates/
// │ ├── core/ (共享库)
// │ │ └── src/lib.rs (数据模型、业务逻辑)
// │ ├── server/ (Web后端)
// │ │ └── src/main.rs (Axum API服务)
// │ ├── cli/ (CLI工具)
// │ │ └── src/main.rs (命令行客户端)
// │ └── wasm/ (WASM前端)
// │ └── src/lib.rs (浏览器组件)
// └── migrations/ (数据库迁移)
use std::collections::HashMap;
#[derive(Debug, Clone)]
pub enum Priority { Low, Medium, High, Critical }
impl std::fmt::Display for Priority {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Priority::Low => write!(f, "低"),
Priority::Medium => write!(f, "中"),
Priority::High => write!(f, "高"),
Priority::Critical => write!(f, "紧急"),
}
}
}
#[derive(Debug, Clone)]
pub struct Task {
pub id: u64,
pub title: String,
pub description: String,
pub completed: bool,
pub priority: Priority,
pub tags: Vec<String>,
}
pub struct TaskManager {
tasks: HashMap<u64, Task>,
next_id: u64,
}
impl TaskManager {
pub fn new() -> Self { TaskManager { tasks: HashMap::new(), next_id: 1 } }
pub fn add(&mut self, title: &str, desc: &str, priority: Priority, tags: Vec<String>) -> u64 {
let id = self.next_id; self.next_id += 1;
self.tasks.insert(id, Task { id, title: title.into(), description: desc.into(), completed: false, priority, tags });
id
}
pub fn complete(&mut self, id: u64) -> Result<(), String> {
self.tasks.get_mut(&id).ok_or("未找到任务")?.completed = true;
Ok(())
}
pub fn list_all(&self) -> Vec<&Task> { self.tasks.values().collect() }
pub fn list_pending(&self) -> Vec<&Task> {
self.tasks.values().filter(|t| !t.completed).collect()
}
pub fn list_by_tag(&self, tag: &str) -> Vec<&Task> {
self.tasks.values().filter(|t| t.tags.iter().any(|t2| t2 == tag)).collect()
}
pub fn stats(&self) -> (usize, usize, usize) {
let total = self.tasks.len();
let done = self.tasks.values().filter(|t| t.completed).count();
(total, done, total - done)
}
}
fn main() {
let mut tm = TaskManager::new();
tm.add("学习Rust", "完成Rust语言入门课程", Priority::High, vec!["学习".into()]);
tm.add("构建API", "用Axum构建REST API", Priority::Medium, vec!["开发".into()]);
tm.add("写文档", "为项目编写文档", Priority::Low, vec!["文档".into()]);
tm.add("紧急修复", "修复生产环境bug", Priority::Critical, vec!["运维".into(), "紧急".into()]);
println!("📋 所有任务:");
for task in tm.list_all() {
let status = if task.completed { "✅" } else { "⬜" };
println!(" {} [{}] {} - {}", status, task.priority, task.title, task.description);
}
tm.complete(1).unwrap();
let (total, done, pending) = tm.stats();
println!("\n📊 统计: 共{}项, 完成{}项, 待办{}项", total, done, pending);
println!("\n🎓 恭喜完成Rust语言入门全部25课!");
println!("🦀 你已经掌握了:");
println!(" ✅ 所有权与借用");
println!(" ✅ 类型系统与泛型");
println!(" ✅ trait与生命周期");
println!(" ✅ 错误处理模式");
println!(" ✅ 并发与异步编程");
println!(" ✅ 宏与元编程");
println!(" ✅ FFI与unsafe");
println!(" ✅ CLI、Web、数据库、WASM开发");
println!("\n🚀 下一步:构建你自己的Rust项目!");
}
✅ 验证通过
你现在是Rust开发者了!🦀🎉
use std::collections::HashMap;
#[derive(Debug, Clone)]
struct TaskDto { id: u64, title: String, priority: String, completed: bool }
struct TaskService { tasks: HashMap, next_id: u64 }
impl TaskService {
fn new() -> Self { TaskService { tasks: HashMap::new(), next_id: 1 } }
fn create(&mut self, title: &str, priority: &str) -> TaskDto {
let id = self.next_id; self.next_id += 1;
let t = TaskDto { id, title: title.into(), priority: priority.into(), completed: false };
self.tasks.insert(id, t.clone()); t
}
fn complete(&mut self, id: u64) -> Option {
if let Some(t) = self.tasks.get_mut(&id) { t.completed = true; Some(t.clone()) } else { None }
}
fn summary(&self) -> (usize, usize) {
let total = self.tasks.len();
let done = self.tasks.values().filter(|t| t.completed).count();
(total, done)
}
}
fn main() {
let mut svc = TaskService::new();
svc.create("学Rust", "高"); svc.create("做项目", "中"); svc.create("写文档", "低");
svc.complete(1);
let (total, done) = svc.summary();
println!("📊 总计{}项, 完成{}项", total, done);
println!("
🎓 毕业!推荐继续:");
println!(" 📖 Rust系统编程进阶");
println!(" 🔨 构建开源项目");
println!(" 🌟 贡献Rust生态");
}
✅ 验证通过
fn main() {
println!("🦀 Rust开发者成长路线:");
println!();
println!("入门 (你在这里!) ────────────────");
println!(" ✅ 所有权与借用");
println!(" ✅ 类型系统与泛型");
println!(" ✅ 错误处理与测试");
println!(" ✅ 并发与异步");
println!(" ✅ 宏与FFI");
println!();
println!("进阶 ────────────────");
println!(" 🔲 系统编程深入");
println!(" 🔲 网络编程精通");
println!(" 🔲 性能优化与profiling");
println!(" 🔲 为标准库贡献");
println!();
println!("精通 ────────────────");
println!(" 🔲 编译器插件");
println!(" 🔲 过程宏框架");
println!(" 🔲 嵌入式Rust");
println!(" 🔲 Rust语言设计参与");
println!();
println!("推荐资源:");
println!(" 📖 The Rust Programming Language (官方书)");
println!(" 📖 Rust for Rustaceans (进阶)");
println!(" 📖 Zero to Production in Rust (Web开发)");
println!(" 🌐 https://rustlings.cool (练习)");
println!(" 🌐 https://exercism.org/tracks/rust (练习)");
println!(" 🌐 https://areweasyncyet.rs (异步生态)");
println!(" 🌐 https://thisweekinrust.org (周报)");
println!("
🦀 恭喜毕业!Rust之旅,永无止境!");
}
use std::collections::HashMap;
#[derive(Debug, Clone)]
struct Task {
id: u64, title: String, description: String,
priority: Priority, completed: bool, tags: Vec,
}
#[derive(Debug, Clone, PartialEq)]
enum Priority { Low, Medium, High, Critical }
impl std::fmt::Display for Priority {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let s = match self { Priority::Low=>"低", Priority::Medium=>"中", Priority::High=>"高", Priority::Critical=>"紧急" };
write!(f, "{}", s)
}
}
struct TaskManager { tasks: HashMap, next_id: u64 }
impl TaskManager {
fn new() -> Self { TaskManager { tasks: HashMap::new(), next_id: 1 } }
fn add(&mut self, title: &str, desc: &str, priority: Priority, tags: Vec<&str>) -> u64 {
let id = self.next_id; self.next_id += 1;
self.tasks.insert(id, Task {
id, title: title.into(), description: desc.into(),
priority, completed: false, tags: tags.into_iter().map(String::from).collect(),
}); id
}
fn complete(&mut self, id: u64) -> Result<(), String> {
self.tasks.get_mut(&id).ok_or("未找到")?.completed = true; Ok(())
}
fn pending(&self) -> Vec<&Task> { self.tasks.values().filter(|t| !t.completed).collect() }
fn completed(&self) -> Vec<&Task> { self.tasks.values().filter(|t| t.completed).collect() }
fn by_tag(&self, tag: &str) -> Vec<&Task> {
self.tasks.values().filter(|t| t.tags.iter().any(|t2| t2 == tag)).collect()
}
fn stats(&self) -> (usize, usize, usize) {
let total = self.tasks.len();
let done = self.completed().len();
(total, done, total - done)
}
}
fn main() {
let mut tm = TaskManager::new();
tm.add("学习Rust", "完成25课", Priority::High, vec!["学习"]);
tm.add("构建CLI", "用clap开发", Priority::Medium, vec!["开发", "CLI"]);
tm.add("Web API", "Axum REST服务", Priority::Medium, vec!["开发", "Web"]);
tm.add("WASM前端", "浏览器界面", Priority::Low, vec!["前端"]);
tm.add("部署上线", "Docker+CI/CD", Priority::Critical, vec!["运维"]);
tm.complete(1).unwrap();
tm.complete(5).unwrap();
println!("📋 全栈Rust任务管理器");
println!("════════════════════════");
println!("待办任务:");
for t in tm.pending() { println!(" [⬜][{}] {} - {}", t.priority, t.title, t.description); }
println!("已完成:");
for t in tm.completed() { println!(" [✅][{}] {} - {}", t.priority, t.title, t.description); }
let (total, done, pending) = tm.stats();
println!("════════════════════════");
println!("总计{}项 | 完成{}项 | 待办{}项", total, done, pending);
println!("完成率: {:.0}%", done as f64 / total as f64 * 100.0);
println!("
🦀🎓 恭喜完成Rust语言入门全部25课!");
println!("你的Rust之旅才刚刚开始,继续探索吧!");
}
✅ 验证通过
fn main() {
println!("📚 推荐学习路径:");
println!();
println!("入门完成 → 巩固基础:");
println!(" Rustlings: https://rustlings.cool");
println!(" Exercism: https://exercism.org/tracks/rust");
println!();
println!("进阶提升:");
println!(" Rust for Rustaceans (Jon Gjengset)");
println!(" Zero to Production in Rust (Luca Palmieri)");
println!(" Rust in Action (Tim McNamara)");
println!();
println!("社区:");
println!(" This Week in Rust: https://thisweekinrust.org");
println!(" Rust Reddit: r/rust");
println!(" Rust Discord: Rust Community Server");
println!();
println!("实践:");
println!(" 为开源项目贡献PR");
println!(" 参加Rust Hackathon");
println!(" 发布自己的crate");
println!(" 写技术博客分享");
}
use std::collections::HashMap;
// === 全栈Rust应用核心实现 ===
#[derive(Debug, Clone)]
enum Priority { Low, Medium, High, Critical }
impl std::fmt::Display for Priority {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", match self { Priority::Low=>"低", Priority::Medium=>"中", Priority::High=>"高", Priority::Critical=>"紧急" })
}
}
#[derive(Debug, Clone)]
struct Task { id: u64, title: String, desc: String, priority: Priority, done: bool, tags: Vec }
struct TaskManager { tasks: HashMap, next_id: u64 }
impl TaskManager {
fn new() -> Self { TaskManager { tasks: HashMap::new(), next_id: 1 } }
fn add(&mut self, title: &str, desc: &str, p: Priority, tags: Vec<&str>) -> u64 {
let id = self.next_id; self.next_id += 1;
self.tasks.insert(id, Task { id, title: title.into(), desc: desc.into(), priority: p, done: false, tags: tags.into_iter().map(String::from).collect() }); id
}
fn complete(&mut self, id: u64) -> Result<(), String> { self.tasks.get_mut(&id).ok_or("未找到")?.done = true; Ok(()) }
fn list(&self) -> Vec<&Task> { let mut v: Vec<_> = self.tasks.values().collect(); v.sort_by_key(|t| t.id); v }
fn pending(&self) -> Vec<&Task> { self.tasks.values().filter(|t| !t.done).collect() }
fn stats(&self) -> (usize, usize) { let t = self.tasks.len(); (t, self.tasks.values().filter(|t| t.done).count()) }
}
fn main() {
let mut tm = TaskManager::new();
tm.add("学Rust所有权", "25课完整学习", Priority::High, vec!["学习"]);
tm.add("构建CLI工具", "clap框架开发", Priority::Medium, vec!["开发", "CLI"]);
tm.add("Web API服务", "Axum框架实战", Priority::Medium, vec!["开发", "Web"]);
tm.add("WASM前端", "浏览器运行Rust", Priority::Low, vec!["前端", "WASM"]);
tm.add("部署上线", "Docker+CI/CD", Priority::Critical, vec!["运维"]);
tm.complete(1).unwrap();
tm.complete(5).unwrap();
println!("🦀 全栈Rust任务管理器");
println!("══════════════════════════");
println!("待办:");
for t in tm.pending() { println!(" ⬜[{}] {}", t.priority, t.title); }
println!("完成:");
for t in tm.list().iter().filter(|t| t.done) { println!(" ✅[{}] {}", t.priority, t.title); }
let (total, done) = tm.stats();
println!("══════════════════════════");
println!("共{}项 | 完成{}项 | 待办{}项", total, done, total-done);
println!("完成率: {:.0}%", done as f64 / total as f64 * 100.0);
println!("
🎉🦀 恭喜完成Rust语言入门全部25课!");
println!("Rust之旅,永无止境!继续探索吧!");
}
✅ 验证通过