Pattern trong Rust
Thư viện chuẩn của Rust thể hiện các trừu tượng không tốn chi phí thông qua hệ kiểu của nó.
| Pattern | Ở đâu | Tác dụng |
|---|---|---|
| Iterator / Đánh giá lười | core/iter/traits/iterator.rs | Trait Iterator — next() + map/filter/fold có thể ghép |
| Copy-on-Write | alloc/src/borrow.rs | Cow<'a, B> — smart pointer clone-on-write cho parse zero-copy |
| Arena Allocator | bumpalo lib.rs | Bump — arena allocator chuẩn của Rust, dùng trong wasm-bindgen và Deno |
| Work Stealing | Tokio worker.rs | Core::steal_work — work stealing của runtime async đa luồng |
| Dependency Graph | Cargo resolver/ | Phân giải dependency dựa trên DAG cho thứ tự biên dịch crate |
| Reference Counting | alloc/src/sync.rs | Arc<T> — reference counting nguyên tử cho quyền sở hữu chung giữa các thread |
| Interning | rustc symbol.rs | Symbol là một index u32 vào interner toàn cục — mọi identifier đều intern để so sánh O(1) |
| Semaphore | Tokio semaphore.rs | Semaphore — kiểm soát concurrency có giới hạn nhận biết async |
Cách chúng kết hợp: Biên dịch một crate
Khi cargo build biên dịch một crate Rust, compiler và runtime dùng các pattern này cùng nhau:
cargo build▼Cargo resolves the crate dependency DAG and determines compilation order. Independent crates compile in parallel.
rustc interns all identifiers into a global table. Every variable name, type name, and keyword becomes a u32 index. Comparison is O(1) integer equality instead of string compare.
The compiler allocates AST nodes and type info in per-query arenas. When a query completes, the entire arena is freed — no per-node deallocation overhead.
Tokio's multi-thread runtime (used by async Rust programs) steals tasks from idle workers' queues to keep all cores busy.
Arc<T> enables shared ownership across threads without a GC. The compiler's type system guarantees no data races.
Triết lý zero-cost abstractions của Rust có nghĩa là các pattern này không có chi phí runtime nào vượt quá những gì một bản triển khai C viết tay phải chịu. Trait Iterator biên dịch xuống cùng machine code như vòng lặp thủ công. Cow<T> tránh clone khi dữ liệu chỉ được đọc. Arc<T> chỉ dùng thao tác nguyên tử khi thực sự được chia sẻ.