Comptime
Comptime means that some of the code in a Zig program will run at compile-time.
Unused code
One surprising aspect of comptime is that code that definitely won’t be used isn’t even compiled. That means unused code doesn’t have to be valid:
const std = @import("std");
const print = std.debug.print;
fn foo() u64 {
return "hello"; // invalid: wrong type
}
pub fn main() void {
const a = "comptime";
if (false) {
a = "runtime"; // invalid: 'a' is const
}
print("Hello, {s}!\n", .{a});
}The program as a whole is fine.
$ zig run comptime.zig
Hello, comptime!
Compile-time calculations
Comptime lets us use Zig code to calculate values that are needed at compile time, such as the length of an array:
const std = @import("std");
const print = std.debug.print;
fn arrayLen(a: u64, b: u64) u64 {
return a * b;
}
pub fn main() void {
// 'comptime' means the expression is evaluated at
// compile time.
const len = comptime arrayLen(2, 3);
const array: [len]u8 = @splat(0xff);
const i = len - 1;
print("array[{}] is {}\n", .{ i, array[i] });
}$ zig run comptime-2.zig
array[5] is 255
Conditional compilation
Another use of comptime is conditional compilation. For example, we can compile different code depending on the operating system:
const std = @import("std");
const print = std.debug.print;
const builtin = @import("builtin");
pub fn main() void {
switch (comptime builtin.os.tag) {
.linux => print("Hello, Linux!\n", .{}),
.macos => print("Hello, Mac OS!\n", .{}),
else => print("Hello, another OS?\n", .{}),
}
}$ zig run comptime-3.zig
Hello, Linux!
For this simple example, we can write the equivalent program by hand:
const std = @import("std");
const print = std.debug.print;
pub fn main() void {
print("Hello, Linux!\n", .{});
}And verify that the result is exactly the same (at least in ReleaseSmall build mode).
$ zig build-exe -O ReleaseSmall comptime-3.zig
$ zig build-exe -O ReleaseSmall comptime-4.zig
$ md5sum comptime-3 comptime-4
7d418de86e2477efe2cec7d9f74f5c3e comptime-3
7d418de86e2477efe2cec7d9f74f5c3e comptime-4
We’ll take a look at some other uses of comptime over the next few examples.
Next example: Precomputed Data.