Skip to content

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Ở đâuTác dụng
Iterator / Đánh giá lườicore/iter/traits/iterator.rsTrait Iteratornext() + map/filter/fold có thể ghép
Copy-on-Writealloc/src/borrow.rsCow<'a, B> — smart pointer clone-on-write cho parse zero-copy
Arena Allocatorbumpalo lib.rsBump — arena allocator chuẩn của Rust, dùng trong wasm-bindgen và Deno
Work StealingTokio worker.rsCore::steal_work — work stealing của runtime async đa luồng
Dependency GraphCargo resolver/Phân giải dependency dựa trên DAG cho thứ tự biên dịch crate
Reference Countingalloc/src/sync.rsArc<T> — reference counting nguyên tử cho quyền sở hữu chung giữa các thread
Interningrustc symbol.rsSymbol là một index u32 vào interner toàn cục — mọi identifier đều intern để so sánh O(1)
SemaphoreTokio semaphore.rsSemaphore — 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
1
Dependency Graph

Cargo resolves the crate dependency DAG and determines compilation order. Independent crates compile in parallel.

2
Interning

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.

3
Arena Allocator

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.

4
Work Stealing

Tokio's multi-thread runtime (used by async Rust programs) steals tasks from idle workers' queues to keep all cores busy.

5
Reference Counting

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ẻ.

Đọc thêm

Released under the MIT License.