typestar

comptime in Zig

The same language runs at compile time: a Fibonacci number baked into the binary.

const std = @import("std");

// Anything computable from constants can run during compilation.
fn fib(n: u32) u32 {
    if (n < 2) return n;
    return fib(n - 1) + fib(n - 2);
}

pub fn main() void {
    const at_build = comptime fib(12);
    std.debug.print("fib(12) baked into the binary: {d}\n", .{at_build});

    comptime var total = 0;
    inline for (.{ 3, 5, 7 }) |x| total += x;
    std.debug.print("summed during compilation: {d}\n", .{total});
}

How it works

  1. comptime fib(12) runs the recursion during compilation; the binary holds 144.
  2. comptime var mutates during compilation only.
  3. inline for unrolls over the tuple, folding the sum before the program exists.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
429
Tokens
122
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 113 seconds.

Type this snippet

Step 1 of 3 in comptime, step 16 of 27 in Language basics.

← Previous Next →