🎓 A1Learner
🔍
0 of 46 lessons completed

Zig Safety Modes

Runtime safety is a set of checks that stop a program when an operation would break a rule. Zig turns these checks on in debug builds and off in fast release builds.

Safety on for one function

@setRuntimeSafety with true turns safety on for its function. The addition here stays in range, so the result is 42.

const std = @import("std");
fn addChecked(a: u8, b: u8) u8 {
    @setRuntimeSafety(true);
    return a + b;
}
pub fn main() !void {
    const out = std.io.getStdOut().writer();
    try out.print("{d}\n", .{addChecked(40, 2)});
}

Safety off for one function

@setRuntimeSafety with false turns safety off for its function. The same in-range addition still gives 42.

const std = @import("std");
fn addUnchecked(a: u8, b: u8) u8 {
    @setRuntimeSafety(false);
    return a + b;
}
pub fn main() !void {
    const out = std.io.getStdOut().writer();
    try out.print("{d}\n", .{addUnchecked(40, 2)});
}

An index inside the array

Safety also guards array indexes. Index 2 is inside this array, so the program prints the third value.

const std = @import("std");
pub fn main() !void {
    @setRuntimeSafety(true);
    const out = std.io.getStdOut().writer();
    const data = [_]u32{ 5, 10, 15, 20 };
    try out.print("{d}\n", .{data[2]});
}

Example

const std = @import("std");
fn addChecked(a: u8, b: u8) u8 {
    @setRuntimeSafety(true);
    return a + b;
}
fn addUnchecked(a: u8, b: u8) u8 {
    @setRuntimeSafety(false);
    return a + b;
}
pub fn main() !void {
    const out = std.io.getStdOut().writer();
    try out.print("{d} {d}\n", .{ addChecked(40, 2), addUnchecked(40, 2) });
}

Key points

  • Runtime safety: runtime safety is a set of checks that catch mistakes while a program runs.
  • Safety check: a safety check is a test that stops a program when a value would break a rule.
  • Debug build: a debug build is a build made for finding mistakes, with safety checks on.
  • Release build: a release build is a build made for speed, with fewer safety checks than a debug build.
  • Safety switch: a safety switch is a builtin that turns runtime safety on or off for one function.
  • Panic: a panic is a program stopping at once when a safety check fails.
  • In-range value: an in-range value is a value that fits its type and stays inside its array.

The two functions differ only in their safety setting. Both return 42 because 42 fits in a u8. An out-of-range input would stop the checked version, while the unchecked version would not be stopped by a safety check.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does @setRuntimeSafety(true) do for its function?