Assertions
An assertion checks a condition that should always be true. You can use them to catch bugs and to serve as documentation for other programmers.
std.debug.assert
asserts that its argument is true:
const std = @import("std");
const print = std.debug.print;
pub fn main() void {
std.debug.assert(1 + 1 == 2);
print("OK\n", .{});
}$ zig run assert.zig
OK
The unreachable keywords asserts that a location in the
code will never be reached:
const std = @import("std");
const print = std.debug.print;
pub fn main() void {
if (1 + 1 == 2) {
print("OK\n", .{});
return;
}
unreachable;
}$ zig run unreachable.zig
OK
If an assertion fails in Debug or ReleaseSafe mode, we get an error message and a stack trace.
In the other modes, a failing assertion is effectively illegal behavior – the idea is that
before you enable ReleaseFast or ReleaseSmall
you’ve done enough testing to be sure there will be no assertion
failures.
Next example: If Statements.