Zig Comptime Validation
Comptime validation is a check that runs while a program is being compiled. A failed check stops the build with a message, so bad values never reach a running program.
Checking A Positive Number
This program checks that 5 is positive. The check passes, so the program prints a confirmation.
const std = @import("std");
fn checkPositive(comptime n: i32) void {
if (n <= 0) @compileError("value must be positive");
}
pub fn main() !void {
const out = std.io.getStdOut().writer();
checkPositive(5);
try out.print("valid\n", .{});
}Checking A Name
This program checks that a name is not empty. The name has letters, so the check passes.
const std = @import("std");
fn checkName(comptime name: []const u8) void {
if (name.len == 0) @compileError("name must not be empty");
}
pub fn main() !void {
const out = std.io.getStdOut().writer();
checkName("ada");
try out.print("name ok\n", .{});
}Checking A Range
This program checks that 7 sits between 1 and 10. The value is inside the range, so the check passes.
const std = @import("std");
fn checkRange(comptime n: i32) void {
if (n < 1 or n > 10) @compileError("value must be between 1 and 10");
}
pub fn main() !void {
const out = std.io.getStdOut().writer();
checkRange(7);
try out.print("in range\n", .{});
}Example
const std = @import("std");
fn checkTimeout(comptime t: u32) void {
if (t == 0) @compileError("timeout must not be zero");
}
fn checkRetries(comptime r: u32) void {
if (r > 5) @compileError("retries must not exceed 5");
}
pub fn main() !void {
const out = std.io.getStdOut().writer();
checkTimeout(30);
checkRetries(3);
try out.print("settings ok\n", .{});
}Key points
- Validation: validation is a check that a value or type meets a rule.
- @compileError: @compileError is a builtin that stops compilation with a message.
- A validation check sits in a comptime branch, so it only fires when its rule fails.
- Valid inputs pass the check silently, and the program runs as normal.
- Validation works for numbers, text, and types, because all of them exist at compile time.
- A clear message names the rule that failed, so the fix is easy to find.
The example checks a timeout and a retry count before the program runs. Both values pass their rules, so no check fires. The program then prints a confirmation line.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What happens when a @compileError check fires?