Zig 高性能编程模式
idiomatic-zig
来自 Ghostty 和 TigerBeetle 的地道、高性能 Zig 生产级编程模式。在编写需要快速、安全且易于维护的 Zig 代码时使用。
- License 许可
- MIT
- 最近更新
- 2026-11-11
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- idiomatic-zig
- description
- Production patterns for idiomatic, high-performance Zig from Ghostty and TigerBeetle. Use when writing Zig code that needs to be fast, safe, and maintainable.
02 资源文件 15
- 脚本check.sh990 B
- 其他examples/assertion_patterns.zig3.6 KB
- 其他examples/comptime_type_generation.zig4.3 KB
- 其他examples/concurrency_patterns.zig7.3 KB
- 其他examples/error_handling_patterns.zig5.6 KB
- 其他examples/generic_type_function.zig3.7 KB
- 其他examples/options_struct.zig3.8 KB
- 其他examples/packed_struct.zig3.4 KB
- 其他examples/static_allocator.zig4.3 KB
- 参考文档references/api-design-patterns.md9.5 KB
- 参考文档references/memory-patterns.md8.0 KB
- 参考文档references/performance-patterns.md7.0 KB
- 参考文档references/safety-and-assertions.md8.0 KB
- 参考文档references/testing-strategies.md9.4 KB
- 参考文档references/tiger-style-principles.md6.1 KB
03 SKILL.md 正文
Idiomatic Zig: Production Patterns from Ghostty & TigerBeetle
Patterns distilled from two flagship Zig projects:
- Ghostty — GPU-accelerated terminal emulator. SIMD optimization, cache-friendly packed structs, offset-based memory addressing, cross-platform abstraction.
- TigerBeetle — Distributed financial database. Static allocation discipline, assertion-driven safety, deterministic simulation testing, io_uring integration. Their TIGER_STYLE.md is one of the best coding style guides ever written.
Target version: Zig 0.16. Every example in examples/ compiles and its tests pass on 0.16.0 — run ./check.sh to re-verify. When using the zig-programming skill alongside this one, defer to its version detection for API specifics.
0.16 moved enough ground that a few of these idioms changed shape rather than wording. std.Io is now an interface value passed like an Allocator. The blocking primitives moved out of std.Thread into std.Io. @Type split into @Struct / @Enum / @Int / @Union / @Pointer. And main receives a std.process.Init carrying a ready-made allocator and Io. Where that changes the advice and not just the spelling, it is called out inline below.
How to Use This Skill
Load this skill alongside zig-programming for production Zig work. This skill provides idioms and design philosophy; zig-programming provides syntax, stdlib reference, and version detection.
Writing a new module: Start with Design Philosophy and Naming & Style, then load the relevant reference for your domain.
Optimizing hot paths: Load references/performance-patterns.md.
Reviewing existing code: Check assertion density (2+ per function), naming conventions, struct field order, and error handling patterns.
Reference Files (load as needed)
references/memory-patterns.md— Allocator strategies, pools, offset addressing, in-place init (grep:StaticAllocator,BitmapAllocator,Offset,mmap,MemoryPool,errdefer,deinit,init.gpa)references/performance-patterns.md— SIMD, cache lines, branch hints, hot loop extraction (grep:@branchHint,@prefetch,packed struct,fastmem,@divExact,cache_line)references/safety-and-assertions.md— Assertion discipline, NASA Power of Ten, pair assertions (grep:assert,fatal,maybe,comptime unreachable,slow_runtime_safety,verify)references/testing-strategies.md— VOPR, fuzz testing, tripwire error injection, coverage marks (grep:tripwire,VOPR,fuzz,coverage,refAllDecls,verifyIntegrity,swarm,testing.io)references/api-design-patterns.md— Options structs, tagged unions, generic type functions,Ioas a dependency (grep:Options,union(enum),TreeType,Renderer,callback,inline else,Io,Cancelable)references/tiger-style-principles.md— Core philosophy from TigerBeetle's style guide (grep:Power of Ten,zero technical debt,70-line,control plane,data plane)
Example Files
examples/assertion_patterns.zig— Comptime assertions, pair assertions, positive/negative spaceexamples/comptime_type_generation.zig— Data table to packed struct + enum + dispatch (@Struct/@Enum)examples/generic_type_function.zig—FooType()pattern with comptime callbacksexamples/options_struct.zig— Named arguments via config struct,Iothreaded positionallyexamples/packed_struct.zig— Cache-friendly Cell/Row layout with fast-path skippingexamples/static_allocator.zig— Three-phase allocator lifecycleexamples/error_handling_patterns.zig— Narrow error sets, translation, errdefer disciplineexamples/concurrency_patterns.zig— Dirty flags, atomics, blocking queues overstd.Io.Mutex
Design Philosophy
Full treatment in
references/tiger-style-principles.md.
Safety, performance, developer experience — in that order. When they conflict, this is the priority. Good style advances all three simultaneously.
Simplicity is the hardest revision, not the first attempt. Spend mental energy upfront in design. The "super idea" that solves multiple axes simultaneously is what to look for.
Zero technical debt. Do it right the first time. What ships must be solid — lacking features is acceptable, lacking quality is not.
Be explicit. No hidden control flow, no hidden allocations, no hidden async. Pass options explicitly. Show intent. Minimize dependence on the compiler to do the right thing.
Put a limit on everything. All loops, queues, and buffers must have a fixed upper bound.
Memory Management
Full treatment and code examples in
references/memory-patterns.md.
Key patterns:
- Choose the right allocator per layer —
init.gpaat top level,ArenaAllocatorfor temp work,MemoryPoolfor fixed-size objects, direct OS allocation for hot paths. In 0.16 do not construct your own top-level allocator:init.gpais already leak-checking in Debug andsmp_allocator/c_allocatorin release. - Static allocation after init — When memory needs are known at startup, allocate everything upfront, then forbid further allocation. A performance choice, not a universal rule.
- In-place initialization — Initialize large structs via out pointers to avoid stack copies. Viral — if any field needs it, the container should too.
- deinit sets undefined — Set
self.* = undefinedafter freeing to catch use-after-free in debug builds. - errdefer discipline — Every fallible init must use
errdeferto clean up partial state.
Safety & Assertions
Full treatment in
references/safety-and-assertions.md.
Key rules:
- Two assertions per function minimum in production logic. Assertions are a force multiplier for fuzzing. Trivial helpers and wrappers are exempt.
- Pair assertions — Assert the same property in two different code paths (e.g., before write AND after read).
- Assert positive AND negative space —
assert(index < length)ANDassert(value != sentinel). - Split compound assertions —
assert(a); assert(b);overassert(a and b)for precise diagnostics. - Comptime assertions — Assert relationships between constants before execution.
- Three-tier error strategy —
assert(programmer errors),fatal(environmental errors), error unions (operational errors).
Performance
Full treatment with SIMD examples in
references/performance-patterns.md.
Key patterns:
- Think performance at design time — The 1000x wins come from design, not profiling. Back-of-the-envelope across network/disk/memory/CPU.
- Packed structs for cache-friendly layout — Design hot data to fit in cache lines. Make the zero value meaningful.
- Row flags for fast-path skipping — Track metadata at the container level to skip expensive per-element work.
@branchHint— Mark cold/unlikely/unpredictable branches explicitly.- Extract hot loops — Remove
selffrom inner-loop functions so the compiler can freely register-allocate. - Show division intent —
@divExact,@divFloor,div_ceilinstead of generic/.
Error Handling
- Narrow error sets — Define operation-specific error sets, not
anyerror. - Error translation at boundaries — Translate subsystem errors to domain-specific names.
errdefer comptime unreachable— After a point where no more errors can occur, document it explicitly.
See examples/error_handling_patterns.zig for complete examples.
Comptime Patterns
Detailed examples in
references/api-design-patterns.mdandexamples/comptime_type_generation.zig.
- Generic data structures via type functions —
pub fn FooType(comptime T: type) type { return struct { ... }; }. - Type generation from data tables — Define data as a table, generate packed structs and enums at comptime. 0.16 replaced
@Typewith one builtin per kind:@Struct(layout, backing_int, names, types, attrs),@Enum(Tag, exhaustiveness, names, values),@Int,@Union,@Pointer. inline elsefor comptime dispatch — Turn runtime enum values into comptime-known values.- Platform selection at comptime —
pub const Io = switch (builtin.target.os.tag) { ... }. - Compile-time layout verification —
comptime { assert(@sizeOf(Cell) == 8); }.
Code Organization
- File-as-struct — Major types get their own
TitleCase.zigfile; the struct is@This(). Lowercase files are namespace modules. - Flat namespacing — Prefer
stdx.PRNGoverstdx.random.PRNG. - Root re-export module — Package root re-exports public types.
- Config/constants split — Raw config in
config.zig, derived constants inconstants.zig. Code importsconstants, neverconfigdirectly. - Struct field order — Fields first, types next, methods last. Important things near the top.
- Scoped logging — Every module:
const log = std.log.scoped(.module_name);. - Modular build system — Keep
build.zigthin; delegate to file-structs insrc/build/.
Naming & Style
Follow the Zig style guide. Where Ghostty and TigerBeetle disagree, the Zig stdlib is the tiebreaker.
Naming Rules
- Types:
TitleCase—ArrayList,Allocator - Functions/methods:
camelCase—insertSlice,appendAssumeCapacity - Functions returning
type:TitleCase—fn ArrayList(comptime T: type) type - Variables and constants:
snake_case—max_connections,timeout_ms_default - File names:
TitleCase.zigfor file-as-struct,snake_case.zigfor namespace modules
Acronyms Are Regular Words
Acronyms follow the same casing rules as any other word, even two-letter ones:
// Correct (stdlib convention):
const XmlParser = struct { ... };
const TcpServer = struct { ... };
const Io = @import("Io.zig");
// Wrong:
const XMLParser = struct { ... };
const IO = @import("IO.zig");
TigerBeetle uses
VSRStateand Ghostty usesIO— both deviate from the stdlib. Follow the stdlib (Io,Uri,Tcp,Tls).
Name Quality
- Units/qualifiers last, by descending significance:
latency_ms_max, notmax_latency_ms. - Same-length related names:
source_offset/target_offset, notsrc_offset/dest_offset. - No abbreviations —
sourceandtarget, notsrcanddest. Exception: primitive loop variables. - Nouns over adjectives —
replica.pipelineoverreplica.preparing. - Infuse meaning —
gpa: Allocatorandarena: Allocatoroverallocator: Allocator.
Formatting
- Run
zig fmt. 4-space indentation. Hard 100-column limit. - Braces on
ifunless it fits on one line. - 70-line function limit. Art is born of constraints.
- Comments are sentences — capital letter, full stop, space after
//. Always say why.
API Design
Full examples in
references/api-design-patterns.md.
- Options structs — When arguments can be mixed up (especially multiple integers), use an options struct. Dependencies stay positional, configuration goes in the struct. 0.16's
net.IpAddress.listen(address, io, options)is the stdlib's own worked example. Iois a dependency, not ambient authority — Passstd.Iolike anAllocator, most-general first (gpa, io, ...). A function with noIoparameter cannot block, touch the disk, or be cancelled — a guarantee the compiler enforces, because everyDirandFileoperation takes anIo.- Tagged unions for state machines — Express multi-state logic as
union(enum), not boolean flags. - Return struct for multiple values —
struct { row: *Row, cell: *Cell }. - Callbacks go last — Mirror control flow. Name with calling function as prefix:
readSector()/readSectorCallback(). - Simpler return types — Reduce dimensionality:
void>bool>u64>?u64>!u64.
Testing
Full treatment in
references/testing-strategies.md.
- Inline tests — Place tests alongside the code they test, not in separate files.
- Size assertions — Guard against accidental layout changes with
expectEqual(@sizeOf(T), N). - Tripwire error injection — Inject errors at specific allocation points to test
errdefercleanup. Zero-cost in production. - Deterministic simulation — Stub all non-determinism (clock, network, disk). Seed + commit = reproducible results.
- Coverage marks — Trace from test to production code, proving the test exercises the intended path.
- Fuzz every data structure — Dedicated fuzzer per major data structure. Use swarm testing for better coverage.
- Integrity verification —
verifyIntegrity()checks all invariants;assertIntegrity()is a no-op in release. refAllDecls— Make sure all declarations at least compile. It is shallow, so also write_ = &Type.method;for I/O-shaped functions that have no unit test — Zig never analyses a function nothing reaches, which is how untested code silently rots across a release.
Concurrency
- Default to single-threaded — Design for single-threaded first. Add concurrency only when proven necessary.
- Run at your own pace — Own the event loop. Batch incoming work, process on your schedule.
- Dirty flags over locks — Signal what needs updating via
packed structflags rather than locking. - Atomic values for cross-thread state —
std.atomic.Value(usize). - Blocking queues — Fixed-capacity
BlockingQueuefor producer-consumer between threads. - io_uring on Linux — Submit batched I/O operations, process completions in a loop. In 0.16 this is
std.Io.Evented, which selects io_uring, kqueue or Dispatch per target.
What Moved in 0.16
The blocking primitives left std.Thread for std.Io, and they take the Io as a parameter:
| 0.15 | 0.16 |
|---|---|
std.Thread.Mutex |
std.Io.Mutex |
std.Thread.RwLock |
std.Io.RwLock |
std.Thread.Condition |
std.Io.Condition |
std.Thread.Semaphore |
std.Io.Semaphore |
std.Thread.ResetEvent |
std.Io.Event |
std.Thread.WaitGroup |
std.Io.Group (async / await / cancel) |
Initialise with the decl literal — mutex: std.Io.Mutex = .init, not = .{}.
Atomics and dirty flags did not move. That is the useful signal: a primitive takes an
Io exactly when it can block. If a type needs no Io, it cannot block, and the signature
says so without a comment.
Cancellation is the new cost. lock(io) returns Cancelable!void. Propagate that when
the wait is genuinely unbounded. Use lockUncancelable(io) when the critical section is
O(1) with no I/O inside it, so a bounded wait does not inflate every caller's return type.
See examples/concurrency_patterns.zig.
Sources
- Ghostty — Mitchell Hashimoto
- TigerBeetle — TigerBeetle team
- TIGER_STYLE.md — TigerBeetle's coding style guide
04 同仓库更多 Skills
Claude 技能创建指南
skill-creator
创建有效技能的指南。当用户想要创建新技能(或更新现有技能),以通过专业知识、工作流或工具集成来扩展 Claude 的能力时,应使用此技能。
素材成文逐段撰写
writing-shape
写作,利用(exploit):将原始素材逐段塑造成一篇文章。
Playwright 网页应用测试
webapp-testing
使用 Playwright 测试本地 Web 应用。适用于验证前端功能、调试 UI 行为、截取浏览器截图或查看浏览器日志。
消息重述
wait-what
停。上一条消息没有被理解(没说清楚):换一种方式重新表述。
快速原型构建
prototype
构建一个一次性原型来回答设计问题。当用户想要验证某个状态模型或逻辑是否合理,或探索 UI 应该是什么样子时使用。
代码库架构优化分析
improve-codebase-architecture
扫描代码库以发现可深化改进的机会,将其以可视化 HTML 报告的形式呈现,然后对你选中的某一项进行深入质询。