⚡ Zig Guide LiveUnofficialbut fully verified
✓ Zig 0.18.0-dev.624+b7f2c6d8fWhat's newOn an older Zig?Blograylib-zig

Comptime

The compiler runs usual Zig code during compilation. Each chapter in this section is one complete program, and CI checks its output. Some programs in this section do not compile, and the lesson is the error. CI checks that the compiler stops with the message that the page shows. The last three chapters are small projects that use the earlier chapters.

  1. A var is never comptime-known, even when no code changes it. A const is comptime-known only when its value is.
  2. A const at the top level of a file always runs during compilation. A CRC-32 table needs no comptime keyword and no script.
  3. Comptime evaluation stops after 1000 backward branches. A 256-entry table with an inner loop of 8 steps needs @setEvalBranchQuota.
  4. @typeInfo lists only the pub declarations of a type.
  5. @Type is gone. Use @Int, @Struct, @Enum, @Union or @Tuple.

11 chapters.

  • Know What the Compiler KnowsThe rule that decides which values the compiler can use, and four ways to use them.
  • Build Lookup TablesThe compiler calculates a CRC-32 table, and the program checks it against the standard library.
  • Read a TypeUse @typeInfo to list the fields of a struct, an enum and a union, then write a generic diff.
  • Make a TypeMake integer, struct, enum and tuple types from comptime values, and write a Partial(T) patch type.
  • Dispatch with ComptimeConnect each tag of an enum to its handler at compile time, with a switch or with a table.
  • Reject Bad Input with @compileErrorCheck the type that a generic function receives, and stop the build with a message that names the problem.
  • Parse Strings at Compile TimeParse a route pattern during compilation, and make a struct type for its parameters.
  • Know the LimitsWhat comptime code cannot do, what to use instead, and what comptime costs.
  • Project: Units of MeasureA number type that carries its unit. Metres times metres is an area, and metres plus seconds does not compile.
  • Project: Parse Arguments from a StructThe fields of a struct are the options. The compiler makes the parser and the help text.
  • Project: A Typed Event BusHandlers are plain functions. The bus reads their parameter types and connects each one to its event during compilation.