← 返回日报
精读 预计 1 分钟

Zig by Example

摘要

该教程通过 40 个带注释的示例系统地介绍了 Zig 语言,涵盖基础语法、控制流、Comptime、内存管理、标准库用法及 C 语言互操作等内容。其设计初衷是展示 Zig 简洁、无隐藏分配和控制流的特性,目前针对 Zig 0.14 版本。

荐读理由

在评估高性能 AI 算子或底层系统组件的选型时,你可以通过这些覆盖内存分配、Comptime 及 C 互操作的示例代码,快速判断 Zig 这种无隐藏分配的语言是否能解决你项目中的性能瓶颈。

原文

Zig by Example

Zig 0.16 License: CC BY 4.0

Read online: boring.college/books/zig-by-example

A hands-on introduction to Zig via annotated examples. Zig is a general-purpose, compiled systems language focused on robustness, optimality, and simplicity — no hidden control flow, no hidden allocations, no preprocessor.

Written by Dariush Abbasi for Boring College


Layout

  • chapters/NN-name.md — the annotated chapter

  • examples/NN-name.zig — the runnable source

Every code block in chapters/ mirrors the matching examples/*.zig file and has been compiled against the target Zig version.

Index

  1. Hello, World

  2. Values

  3. Variables

  4. Integers

  5. Floats

  6. Strings

  7. Arrays

  8. Slices

  9. Vectors

  10. Structs

  11. Enums

  12. Unions

  13. Functions

  14. Blocks and Statements

  15. If / Else

  16. Switch

  17. While Loops

  18. For Loops

  19. Defer

  20. Errors

  21. Optionals

  22. Pointers

  23. Multi-Pointers

  24. Slices (Pointers)

  25. Comptime

  26. Generics

  27. Memory Allocation

  28. ArrayList

  29. HashMap

  30. Linked List

  31. Testing

  32. Formatting and Print

  33. Io Interfacenew in 0.16

  34. Writer & Readernew

  35. File I/O

  36. Threading & Concurrencynew

  37. Processes

  38. Networking & HTTPnew

  39. JSON

  40. Random Numbers

  41. Sorting

  42. Math

  43. Build System

  44. C Interop


Running the examples

Install Zig 0.16.0 — brew install zig on macOS, or grab a tarball from ziglang.org/download. Then:

$ zig run examples/01-hello-world.zig
Hello, World!

A few examples need extra flags:

$ zig test examples/31-testing.zig            # tests
$ zig run  examples/44-c-interop.zig -lc      # link libc

Further Reading


Zig by Example is inspired by Go by Example by Mark McGranaghan. Examples target Zig 0.16.

Contributions welcome — see CONTRIBUTING.md.

Hacker News · 90 赞 · 19 评 讨论 → 阅读原文 →

这条对你有帮助吗?