Danh sách bài viết

Rust Cơ Bản - Học Rust Từ Zero Đến Sẵn Sàng Viết Web Service

Series Rust Cơ Bản với 316 bài học, chia thành 39 nhóm, dành cho người chưa biết Rust hoặc đã thử nhưng đầu hàng vì borrow checker. Học từ cài đặt rustup, syntax cơ bản, đến những concept khó nhất của Rust (ownership, borrow, lifetime), rồi tiếp tục với trait, generic, error handling, smart pointer, concurrency, async/await và tokio basic. Mục tiêu: sau khi xong series này, bạn có đủ nền tảng để bước vào series Rust RESTful API — học viết web service production-grade với axum, sqlx, tower middleware, JWT, observability.

09/06/2026
15 phút đọc
2 lượt xem
Rust Cơ Bản - Học Rust Từ Zero

Mục Tiêu Series

  • Học Rust 2024 edition từ zero — không cần kinh nghiệm trước. Nắm vững ownership / borrow / lifetime (3 concept khiến đa số bỏ cuộc), hiểu sâu trait & generic, dùng được Result / Option / ? thuần thục, biết viết test, dùng được tokio basic và async/await. Đầu ra: tự build CLI tool đơn giản, web scraper, HTTP client trong terminal — và sẵn sàng bước vào rust-restful để học viết API service production.

Prerequisites

  • ✅ Đã từng viết code ở 1 ngôn ngữ bất kỳ (JS, Python, Java, Go, C/C++...)
  • ✅ Hiểu khái niệm hàm, biến, vòng lặp, struct/class
  • ✅ Terminal cơ bản (chạy lệnh, cd, ls)
  • ✅ Git cơ bản (clone, commit, push)
  • 📝 Kinh nghiệm C/C++ (helpful cho ownership/pointer nhưng KHÔNG bắt buộc)
  • 📝 Đã biết khái niệm stack vs heap (sẽ ôn lại)
  • ❌ Không cần biết Rust trước đó
  • ❌ Không cần kinh nghiệm system programming

Ai Nên Học Series Này?

  • Backend Engineer đang viết Node/Python/Go muốn chuyển sang Rust cho hot path / latency-critical service
  • Developer C/C++ muốn dùng ngôn ngữ an toàn bộ nhớ tương đương performance
  • Người tò mò Rust nhiều năm nhưng "đầu hàng" lần trước vì borrow checker
  • Frontend / Fullstack muốn học Rust để viết WASM, tooling (như swc, biome)
  • DevOps / SRE muốn viết CLI tool, operator nhỏ bằng Rust
  • Sinh viên / người mới muốn bắt đầu với ngôn ngữ "if it compiles, it works"

Ứng Dụng Sau Khi Học

  • Viết CLI tool nhỏ, fast, single-binary (ripgrep / fd / bat clone)
  • Viết web scraper concurrent dùng reqwest + tokio
  • Đọc / hiểu source code của crate phổ biến (serde, tokio, axum)
  • Debug lỗi compile borrow checker không bỏ cuộc
  • Học tiếp framework web Rust (axum, actix-web, rocket) không bị shock
  • Code review Rust PR ở mức cơ bản (idiom, anti-pattern)

Thời Gian Học

  • Ước tính: 8-10 tuần
  • Tổng số bài: 316 bài học
  • Thời lượng mỗi bài: 7-15 phút (đọc + gõ code)
  • Thực hành: 1.5-2 giờ/ngày
  • Pace khuyến nghị: ~35-40 bài/tuần
  • Capstone projects cuối series: 1 tuần

Tools & Công Nghệ

  • Rust toolchain stable (1.83+ ở thời điểm 2026)
  • Cargo (build, test, doc, publish — all-in-one)
  • rustup (toolchain manager)
  • VS Code + rust-analyzer (khuyến nghị) hoặc RustRover
  • rustfmt + clippy (format + lint built-in)
  • tokio (async runtime — dùng từ group 31)

Cấu Trúc Mỗi Bài

  • 📖 Mục Tiêu: liệt kê 4-6 thứ sẽ nắm được sau bài
  • 💻 Code Example: snippet chạy được, có chú thích
  • ✍️ Giải thích từng bước: không bỏ qua "magic"
  • 🐛 Common Pitfalls: lỗi compile thường gặp & fix
  • 💡 Tips: idiom Rust, anti-pattern tránh
  • 🎯 Bài Tập Củng Cố: 5 câu hỏi + đáp án giấu

Capstone Projects

  • CLI tool với clap — wc (word count) clone
  • File processor — đếm word/line song song với rayon
  • Concurrent web scraper — reqwest + tokio + semaphore rate limit
  • HTTP client trong terminal — curl-like fetcher
  • Tổng kết: checklist tự đánh giá + roadmap rust-restful

Series Tiếp Theo

  • Rust RESTful API — Viết web service production-grade bằng Rust: framework axum / actix-web, tower middleware, sqlx + Postgres, JWT auth, rate limiting, structured logging (tracing), OpenTelemetry, deployment Docker + Kubernetes. Kế thừa trực tiếp Rust Cơ Bản.
  • (Coming) Rust Thực Chiến — Kafka consumer, gRPC service với tonic, WebSocket realtime, CLI tool nâng cao, plugin system, FFI với C, build cho WASM target.

Danh Sách Bài Học (39 Nhóm — 316 Bài)

1. Giới thiệu Rust

  • Rust là gì? Tổng quan ngôn ngữ
  • Lịch sử Rust & vị thế 2026
  • Ưu điểm cốt lõi: safety, performance, ergonomics
  • Rust vs C/C++ — khi nào chọn
  • Rust vs Go / Node / Python
  • +3 bài nữa...

2. Cài đặt môi trường

  • Yêu cầu hệ thống cho Rust
  • Cài rustup trên macOS / Linux / Windows
  • Toolchain stable / beta / nightly
  • rustup update & component
  • VS Code + rust-analyzer
  • +3 bài nữa...

3. Cargo cơ bản

  • Cargo là gì? Vai trò trong project
  • cargo new vs cargo init
  • Cấu trúc thư mục mặc định
  • Cargo.toml anatomy
  • cargo build / run / check
  • +3 bài nữa...

4. Variables & Mutability

  • let — binding cơ bản
  • mut — biến mutable
  • Shadowing — re-bind cùng tên
  • const vs let
  • static variable
  • +1 bài nữa...

5. Scalar Types

  • Integer signed (i8 → i128, isize)
  • Integer unsigned (u8 → u128, usize)
  • Integer overflow — debug vs release
  • Floating-point f32, f64
  • Bool, char (4 bytes Unicode)
  • +3 bài nữa...

6. Compound Types

  • Tuple — nhóm giá trị khác loại
  • Tuple destructuring
  • Array — fixed-size collection
  • Array indexing & length
  • Slice preview &[T]

7. Functions & Control Flow

  • fn — định nghĩa function
  • Parameters & return type
  • Expression vs Statement
  • if / else as expression
  • loop, while, for
  • +3 bài nữa...

8. Strings cơ bản

  • String vs &str — khái niệm cốt lõi
  • String literal &'static str
  • String::new / from / to_string
  • UTF-8 — vì sao không index bằng [i]
  • format! macro & concatenation
  • +1 bài nữa...

9. Ownership (concept lõi)

  • Tại sao Rust có Ownership
  • Stack vs Heap refresher
  • 3 quy tắc Ownership
  • Move semantics — let s2 = s1
  • Copy trait — primitives
  • +5 bài nữa...

10. References & Borrowing

  • & — immutable reference
  • &mut — mutable reference
  • Quy tắc borrowing
  • Dangling reference
  • Non-Lexical Lifetime (NLL)
  • +3 bài nữa...

11. Slices

  • String slice &str
  • Array slice &[T]
  • Range syntax 0..5, ..5, 2..
  • Mutable slice &mut [T]
  • Slice trong function signature
  • +1 bài nữa...

12. Structs

  • Định nghĩa struct
  • Khởi tạo instance
  • Field init shorthand
  • Struct update syntax ..other
  • Tuple struct & unit struct
  • +3 bài nữa...

13. Enums

  • Enum đơn giản
  • Enum variant với data
  • Option<T> — Some/None
  • Result<T,E> overview
  • Method trên enum
  • +3 bài nữa...

14. Pattern Matching

  • match — exhaustive
  • Arm binding & guards
  • Range pattern & multiple |
  • if let / while let / let else
  • Destructure struct/tuple/enum
  • +5 bài nữa...

15. Modules & Crates

  • Package vs Crate vs Module
  • Binary vs Library crate
  • mod keyword & file convention
  • pub visibility
  • use, self/super/crate path
  • +5 bài nữa...

16. Vectors

  • Vec<T> — dynamic array
  • vec! macro & with_capacity
  • push / pop / insert / remove
  • Indexing vs .get()
  • Iterating Vec
  • +3 bài nữa...

17. HashMap & HashSet

  • HashMap<K,V> overview
  • insert / get / remove
  • Entry API — or_insert / and_modify
  • HashMap với custom key
  • HashSet, BTreeMap, BTreeSet
  • +3 bài nữa...

18. Strings nâng cao

  • String capacity & growth
  • push_str / push / concat / +
  • .chars() / .bytes() / .lines()
  • split / splitn / split_whitespace
  • parse() — String → number
  • +1 bài nữa...

19. Error Handling

  • panic! — unrecoverable
  • Result<T,E> — recoverable
  • unwrap vs expect
  • ? operator — propagate
  • Box<dyn Error> universal
  • +5 bài nữa...

20. Generics

  • Generic function — fn largest<T>
  • Generic struct — Point<T>
  • Generic enum — Option/Result
  • Generic method trong impl
  • Trait bound & where clause
  • +3 bài nữa...

21. Traits cơ bản

  • Trait là gì — Rust interface
  • Định nghĩa & impl trait
  • Default method
  • derive macro Debug/Clone/Copy
  • Display vs Debug
  • +5 bài nữa...

22. Traits nâng cao

  • Trait object — dyn Trait
  • Static vs Dynamic dispatch
  • Box<dyn Trait> heterogeneous
  • impl Trait return / argument
  • Supertrait, associated type
  • +3 bài nữa...

23. Lifetimes

  • Lifetime là gì — anti-dangling
  • Annotation 'a, 'b
  • Lifetime trong function & struct
  • Elision rules — 3 quy tắc
  • 'static lifetime
  • +5 bài nữa...

24. Testing

  • cargo test basics
  • #[test] & #[cfg(test)]
  • assert! / assert_eq! / assert_ne!
  • Test trả Result
  • #[should_panic] & #[ignore]
  • +3 bài nữa...

25. Closures

  • Closure syntax |x| x+1
  • Capture: ref / mut ref / move
  • Fn / FnMut / FnOnce
  • Closure as function parameter
  • move keyword & Box<dyn Fn>
  • +3 bài nữa...

26. Iterators

  • Iterator trait — next()
  • iter / into_iter / iter_mut
  • Lazy evaluation
  • collect / sum / count / fold
  • map / filter / take / zip
  • +5 bài nữa...

27. Smart Pointers

  • Box<T> — heap allocation
  • Deref & Drop trait
  • Rc<T> reference counting
  • RefCell<T> interior mutability
  • Rc<RefCell> & Weak pointer
  • +5 bài nữa...

28. Concurrency — Threads

  • thread::spawn & JoinHandle
  • move closure trong spawn
  • Scoped threads (Rust 1.63+)
  • Thread builder & local storage
  • Fix 'may outlive borrowed value'
  • +3 bài nữa...

29. Concurrency — Shared State

  • Send & Sync trait
  • Arc<T> atomic ref count
  • Mutex & Arc<Mutex> pattern
  • RwLock & Atomic types
  • mpsc channel, deadlock, poisoning
  • +5 bài nữa...

30. Async cơ bản

  • Sync vs Async trong Rust
  • async fn & async block
  • Future trait & .await
  • Tại sao không có built-in runtime
  • Cancellation safety, Send Future, Pin
  • +5 bài nữa...

31. Tokio Introduction

  • Cài tokio & features flag
  • #[tokio::main] bootstrap
  • Runtime current vs multi thread
  • tokio::spawn & sleep
  • mpsc / oneshot / broadcast
  • +5 bài nữa...

32. Cargo nâng cao

  • Workspace multi-crate
  • SemVer & versioning
  • Features & optional deps
  • dev / build dependencies
  • cargo update / tree / patch
  • +3 bài nữa...

33. Tools

  • rustfmt auto-format
  • clippy lint
  • rust-analyzer features
  • cargo doc / expand / bench
  • cargo audit / machete / udeps
  • +3 bài nữa...

34. Macros cơ bản

  • macro_rules! declarative
  • Macros vs Functions
  • Common macros built-in
  • Procedural macros overview
  • derive macro & macro hygiene
  • +1 bài nữa...

35. Unsafe Rust

  • Tại sao có unsafe — 5 superpower
  • Raw pointer *const / *mut
  • Dereferencing raw pointer
  • unsafe fn & unsafe trait
  • static mut & FFI extern "C"
  • +1 bài nữa...

36. Standard Library

  • std::io — Read, Write
  • std::fs — File, read_to_string
  • std::path / std::env / std::process
  • std::time — Duration, Instant
  • std::net / std::sync / std::os
  • +5 bài nữa...

37. Logging & Debugging

  • println! / eprintln! / dbg!
  • log crate facade
  • env_logger backend
  • tracing structured logging
  • Panic backtrace & debugger
  • +1 bài nữa...

38. Best Practices

  • Idiomatic Rust — Result over panic
  • anyhow vs thiserror style
  • Project organization
  • Documentation — ///, //!, doc test
  • Testing pyramid, performance, anti-patterns
  • +3 bài nữa...

39. Capstone Projects

  • CLI tool với clap — wc clone
  • File processor parallel với rayon
  • Concurrent web scraper (reqwest + tokio)
  • HTTP client CLI — curl-like
  • Tổng kết & roadmap rust-restful

Tips Học Hiệu Quả

  • Đừng bỏ Ownership: Group 9-11 là "cái cửa" của Rust. Đầu hàng group này = đầu hàng Rust. Dành 1-2 tuần riêng cho ownership/borrow/lifetime.
  • Gõ tay, không copy-paste: Borrow checker chỉ "ngấm" khi bạn nhận lỗi compile thực tế. Copy-paste = miss bài học.
  • Đọc lỗi compile từng dòng: Rust compiler có lỗi cực kỳ thân thiện. Đọc hết, theo gợi ý help:note:.
  • Chạy cargo clippy thường xuyên: Clippy dạy idiom Rust nhanh hơn đọc sách. Coi mọi warning là bài học.
  • Khi bí, dùng cargo expand: Xem macro expand thực sự là gì, bí ẩn biến mất.
  • Tránh học Trait/Generic/Lifetime cùng lúc: Học tuần tự theo thứ tự bài. Đảo lộn = ngợp.
  • Mở std docs song song: Mỗi method gặp lạ, mở docs.rs xem signature đầy đủ.
  • Đọc source std: Vec, HashMap, Option, Result trong stdlib là Rust idiomatic chuẩn — học từ đó.

Lộ Trình Học Tập (8-10 Tuần)

Tuần 1: Khởi động — Giới thiệu, cài đặt, Cargo (Bài 1 - 24)
├── Hiểu vị thế Rust 2026
├── Cài rustup + VS Code + rust-analyzer
└── Cargo workflow: new / build / run / check

Tuần 2: Syntax nền — Variables, types, control flow (Bài 25 - 57)
├── let / mut / shadowing / const
├── Scalar, compound types, strings cơ bản
└── Functions, if/loop/for, expression vs statement

Tuần 3: Ownership trilogy (Bài 58 - 81)
├── Ownership — 3 quy tắc + move/copy
├── References & Borrowing + NLL
└── Slices & UTF-8 pitfalls
⚠️ Tuần khó nhất, đừng vội

Tuần 4: Structs, Enums, Pattern Matching (Bài 82 - 107)
├── Struct + method + associated function
├── Enum + Option/Result + match exhaustive
└── if let / while let / let else

Tuần 5: Modules & Collections (Bài 108 - 139)
├── Package / Crate / Module / pub / use
├── Vec, HashMap, HashSet, BTreeMap
└── String nâng cao + UTF-8 boundaries

Tuần 6: Error Handling + Generics + Traits (Bài 140 - 175)
├── Result + ? + anyhow/thiserror
├── Generic function/struct/method
└── Trait + dyn + impl Trait + associated type

Tuần 7: Lifetimes + Testing + Closures + Iterators (Bài 176 - 211)
├── Lifetime annotation + elision rules
├── #[test] + integration test + fixture
└── Closure (Fn/FnMut/FnOnce) + Iterator chain

Tuần 8: Smart Pointers + Concurrency + Async (Bài 212 - 259)
├── Box / Rc / Arc / Mutex / RefCell
├── thread::spawn + Send/Sync + Channel
└── async/await + tokio basic (spawn, mpsc, select)

Tuần 9: Cargo nâng cao + Tools + Macros + Unsafe (Bài 260 - 297)
├── Workspace + features + cargo audit
├── rustfmt + clippy + rust-analyzer mastery
└── macro_rules! + procedural overview + std review

Tuần 10: Best Practices + Capstone (Bài 298 - 316)
├── Logging (tracing), debugging, idiomatic Rust
├── 4 capstone projects (CLI, file, scraper, HTTP client)
└── Checklist tự đánh giá + roadmap rust-restful