1. 為什麼選擇 Rust?
| 標準 | 鐵鏽 | 去 | C++ |
|---|---|---|---|
| 記憶體安全 | 編譯時(借用檢查器) | 氣相層析 | 手冊 |
| 效能 | 橫向C/C++ | 好(GC 暫停) | 最高 |
| 並發性 | 無畏並發 | Goroutine | 線程+鎖 |
| 零成本抽象 | ✅ | ❌ | ✅ |
| 空安全 | 選項 | 無 | 空指針 |
2.安裝Rust
# Cài rustup (Rust toolchain manager)
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
# Verify
rustc --version
cargo --version
# Update
rustup update
# Components hữu ích
rustup component add clippy # Linter
rustup component add rustfmt # Formatter
3. Cargo——套件管理器和建置工具
# Tạo project mới
cargo new my-app
cd my-app
# Cấu trúc project
# my-app/
# ├── Cargo.toml # Manifest (giống package.json)
# ├── src/
# │ └── main.rs # Entry point
# Cargo.toml
[package]
name = "my-app"
version = "0.1.0"
edition = "2021"
[dependencies]
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1", features = ["full"] }
4.你好世界
fn main() {
let name = "Rust";
println!("Hello, {}!", name);
// Formatted printing
println!("Decimal: {}", 42);
println!("Binary: {:b}", 42);
println!("Debug: {:?}", vec![1, 2, 3]);
println!("Pretty: {:#?}", vec![1, 2, 3]);
}
# Build & Run
cargo run
# Build release
cargo build --release
# Check (compile without codegen — nhanh hơn)
cargo check
# Format code
cargo fmt
# Lint
cargo clippy
下一篇: 變數、類型和控制流。