Zig Builtin Functions
By now you’ve typed @as, @intCast, @TypeOf and @import many times. Anything that starts with @ is a builtin function: it’s built into the compiler itself, not written in Zig, and you can use it anywhere without importing anything. Zig has more than a hundred of them, which looks scary in the reference. The good news is that you’ll use about twenty regularly, and they fall into a few groups. This page is a map: what each common builtin is for, a small example of each group, and what changed in 0.17.
Reading a builtin’s signature
Section titled “Reading a builtin’s signature”The reference lists every builtin with a signature like this:
@intCast(int: anytype) anytype@sizeOf(comptime T: type) comptime_int@min(a: T, b: T, ...) TTwo things in there are worth knowing:
comptimein front of a parameter means you must pass something known at compile time, often a type.@sizeOf(u32)is fine,@sizeOfof a run-time value isn’t.- A return type of
anytypeusually means “the result type comes from where you put the result”.@intCastdoesn’t take a target type: it looks at the variable you’re assigning to. Zig calls that the result type.
That second point explains a pattern you’ve seen everywhere:
const std = @import("std");
pub fn main() void { const big: u32 = 300;
const fits: u16 = @intCast(big); const small: u8 = @truncate(big); const f: f64 = @floatFromInt(big);
std.debug.print("{d} {d} {d}\n", .{ fits, small, f }); std.debug.print("{d}\n", .{@as(u16, @intCast(big)) + 1});}Output:
300 44 300301With const fits: u16 = @intCast(big); the result type is u16, taken from the declaration. In the last line there’s no variable with a type, so @as(u16, ...) provides one. Remember the rule “casts get their target from the left side, or from @as” and most of the casting builtins become easy. Zig Type Casting covers them in detail. (@truncate keeps the low 8 bits of 300, which is 44.)
The map
Section titled “The map”Here are the builtins you’ll actually meet, grouped by what they’re for. The name links to its reference entry.
Casting and conversion
| Builtin | What it does |
|---|---|
@as(T, x) |
Gives x the type T, when that’s always safe. |
@intCast |
Integer to a smaller or different integer type. Panics in safe builds if it doesn’t fit. |
@truncate |
Integer to a smaller one, throwing away the high bits on purpose. |
@floatFromInt |
Integer to float. |
@round, @trunc, @floor, @ceil |
Round a float. With an integer result type, they also convert: const n: i32 = @round(x); |
@floatCast |
Float to a smaller float, like f64 to f32. |
@bitCast |
Same bits, different type, like the bits of an f32 as a u32. |
@ptrCast, @alignCast, @constCast |
Pointer conversions, mostly for C interop. Rare in everyday code. |
Math and bits
| Builtin | What it does |
|---|---|
@min, @max |
Smallest or biggest of two or more values. |
@abs, @sqrt, @sin, @cos, @log |
Common math. There’s no std.math.sin: these are the ones to use. |
@divTrunc, @divFloor, @divCeil, @divExact |
Division with signed integers, where you choose how to round. @divCeil is new in 0.17. |
@rem, @mod |
Remainder with signed integers: @rem keeps the sign of the left side, @mod is never negative (for a positive divisor). |
@addWithOverflow (and sub, mul, shl) |
Do the math and tell you whether it overflowed, instead of panicking. |
@popCount, @clz, @ctz |
Count 1 bits, leading zeros, trailing zeros. |
@byteSwap |
Reverse the byte order of an integer (for file formats and networks). |
Memory and sizes
| Builtin | What it does |
|---|---|
@sizeOf(T) |
Bytes a value of T takes in memory. |
@bitSizeOf(T) |
Bits it really uses (u3 is 3). |
@alignOf(T) |
Its alignment in bytes. |
@memcpy, @memset, @memmove |
Copy bytes, fill bytes, copy when the two areas overlap. |
Enums, errors and unions
| Builtin | What it does |
|---|---|
@tagName |
The name of an enum value or union tag, as a string. |
@errorName |
The name of an error, like "FileNotFound". |
@backingInt, @fromBackingInt |
Enum (or packed struct) to its integer and back. New in 0.17, replacing @intFromEnum and @enumFromInt. |
@unionInit |
Make a union value when the field name is a compile-time string. |
Types, comptime and reflection
| Builtin | What it does |
|---|---|
@TypeOf, @typeName, @typeInfo |
A value’s type, a type’s name, a type’s details. See Zig Reflection. |
@field, @hasField, @hasDecl, @FieldType |
Fields by name, and checks for fields and pub declarations. |
@This() |
The struct you’re inside. See Zig Generic Data Structures. |
@compileError, @compileLog, @setEvalBranchQuota |
Compile-time errors, debugging and budget. See Zig Comptime. |
@inComptime() |
true if the code is running at compile time right now. |
@Int, @Tuple, @Struct, @Enum, @Union, @Pointer, @Fn |
Build a new type from parts, at compile time. They replaced @Type. |
@Vector, @splat, @reduce |
SIMD vectors. See Zig Vectors. |
Files, the build and control
| Builtin | What it does |
|---|---|
@import |
Load another Zig file, std, or builtin (facts about this build). |
@embedFile |
Put a file’s contents into your program as a string, at compile time. |
@src() |
The current file, line, column and function name. |
@panic |
Stop the program with a message (see Zig Unreachable). |
@branchHint |
Tell the optimizer which branch is likely or cold. For later. |
You don’t need to learn these tables. Skim them now, and come back when you wonder “is there a builtin for this?”
Math builtins in action
Section titled “Math builtins in action”const std = @import("std");
pub fn main() void { std.debug.print("min: {d}, max: {d}\n", .{ @min(4, 9, 2), @max(@as(f32, 1.5), 3) }); std.debug.print("abs: {d}, sqrt: {d}\n", .{ @abs(@as(i32, -7)), @sqrt(@as(f64, 2)) });
const a: i32 = -7; const b: i32 = 2; std.debug.print("divTrunc {d}, divFloor {d}, divCeil {d}\n", .{ @divTrunc(a, b), @divFloor(a, b), @divCeil(a, b) }); std.debug.print("rem {d}, mod {d}\n", .{ @rem(a, b), @mod(a, b) });
const result = @addWithOverflow(@as(u8, 250), 10); std.debug.print("250 + 10 in a u8: {d}, overflowed: {d}\n", .{ result[0], result[1] });}Output:
min: 2, max: 3abs: 7, sqrt: 1.4142135623730951divTrunc -3, divFloor -4, divCeil -3rem -1, mod 1250 + 10 in a u8: 4, overflowed: 1-7 / 2 is -3.5, and the three division builtins differ only in how they round it: toward zero (-3), down (-4) or up (-3). For a positive number they’d all agree, which is why Zig only makes you choose for signed integers. @addWithOverflow returns a tuple: the wrapped result (250 + 10 wraps around to 4) and a bit that’s 1 when it overflowed. Use it when overflow is something you want to handle, not a bug. Zig Integer Overflow has more on that.
@abs(@as(i32, -7)) returns a u32, by the way. The absolute value of the smallest i32 doesn’t fit in an i32, so Zig gives you the unsigned type that always fits.
Sizes and bits
Section titled “Sizes and bits”const std = @import("std");
const Pixel = struct { r: u8, g: u8, b: u8, a: u8 };
pub fn main() void { std.debug.print("u32: {d} bytes, Pixel: {d} bytes, u3: {d} bits\n", .{ @sizeOf(u32), @sizeOf(Pixel), @bitSizeOf(u3) });
const flags: u8 = 0b1011_0001; std.debug.print("ones: {d}, leading zeros: {d}, trailing zeros: {d}\n", .{ @popCount(flags), @clz(@as(u8, 0b0001_0000)), @ctz(@as(u8, 0b0001_0000)) });
const bits: u32 = @bitCast(@as(f32, 1.0)); std.debug.print("1.0 as f32 bits: 0x{x}\n", .{bits});}Output:
u32: 4 bytes, Pixel: 4 bytes, u3: 3 bitsones: 4, leading zeros: 3, trailing zeros: 41.0 as f32 bits: 0x3f800000@popCount is a quick way to count how many flags in a bit set are on. @bitCast doesn’t convert the number 1.0 to the integer 1: it keeps the exact 32 bits and just reads them as a u32, which shows how floats are stored. (0.17 changed some @bitCast rules for arrays and vectors; the release notes explain them if you ever need that.)
Enums, errors and memory
Section titled “Enums, errors and memory”const std = @import("std");
const Suit = enum(u8) { hearts = 1, spades = 2 };
pub fn main() void { const s: Suit = .spades; const n = @backingInt(s); const back: Suit = @fromBackingInt(1); std.debug.print("{s} is {d} (a {s}), 1 is {s}\n", .{ @tagName(s), n, @typeName(@TypeOf(n)), @tagName(back) }); std.debug.print("error name: {s}\n", .{@errorName(error.FileNotFound)});
var word: [5]u8 = undefined; @memcpy(&word, "hello"); @memset(word[0..1], 'j'); std.debug.print("{s}\n", .{&word});}Output:
spades is 2 (a u8), 1 is heartserror name: FileNotFoundjello@backingInt gives an enum’s number as exactly its tag type (u8 here), and @fromBackingInt goes back. @memcpy copies into a destination of the same length (it panics in safe builds if they differ), and @memset fills a slice with one value. To copy a short slice into the start of a longer one, slice the destination to fit: @memcpy(dest[0..src.len], src).
Facts about the build: @import("builtin") and @src()
Section titled “Facts about the build: @import("builtin") and @src()”@import("builtin") isn’t a file you can find in the standard library. The compiler writes it for each build, with facts about the target and the options you chose. @src() tells you where in the source you are:
const std = @import("std");const builtin = @import("builtin");
pub fn main() void { std.debug.print("os: {t}, cpu: {t}, mode: {t}\n", .{ builtin.target.os.tag, builtin.target.cpu.arch, builtin.optimize });
const here = @src(); std.debug.print("{s}:{d} in {s}()\n", .{ here.file, here.line, here.fn_name });}On a 64-bit Linux PC you’ll see:
os: linux, cpu: x86_64, mode: debugmain.zig:7 in main()On a Mac or Windows machine, the first line changes. These are compile-time values, so if (builtin.target.os.tag == .windows) only compiles the branch for the system you’re building for. In 0.17, use builtin.target.os, builtin.target.cpu and builtin.target.abi: the short forms builtin.os and builtin.cpu are deprecated and will be removed in 0.18.
Putting a file into your program: @embedFile
Section titled “Putting a file into your program: @embedFile”@embedFile("path") reads a file while compiling and gives you its bytes as a string constant. Handy for help text, templates, small data files or test inputs. The path is relative to the source file. With a greeting.txt next to main.zig:
const std = @import("std");
const greeting = @embedFile("greeting.txt");
pub fn main() void { std.debug.print("{s}", .{greeting}); std.debug.print("{d} bytes, type {s}\n", .{ greeting.len, @typeName(@TypeOf(greeting)) });}If greeting.txt holds two lines, you’ll see:
Hello from a file!Second line.32 bytes, type *const [32:0]u8The file’s contents are now part of the executable: you can copy the program anywhere and it still has them. Change the file and Zig rebuilds. If the file is missing, it’s a compile error, not a run-time one.
Making types: @Int, @Tuple and @Struct
Section titled “Making types: @Int, @Tuple and @Struct”Up to 0.15, Zig had one builtin, @Type, that built any type from a description. It was replaced by one builtin per kind of type: @Int, @Tuple, @Struct, @Enum, @Union, @Pointer and @Fn. You won’t need them often, because a fn Stack(comptime T: type) type returning a struct { ... } covers most generic code. They’re for when even the field names come from data:
const std = @import("std");
fn Flags(comptime names: []const []const u8) type { const types: [names.len]type = @splat(bool); const attrs: [names.len]std.lang.Type.Struct.FieldAttributes = @splat(.{ .default_value_ptr = &false }); return @Struct(.auto, null, names, &types, &attrs);}
const Permissions = Flags(&.{ "read", "write", "delete" });
pub fn main() void { const U18 = @Int(.unsigned, 18); std.debug.print("{s} goes up to {d}\n", .{ @typeName(U18), std.math.maxInt(U18) });
const Entry = @Tuple(&.{ []const u8, u32 }); const e: Entry = .{ "apples", 12 }; std.debug.print("{s}: {d}\n", .{ e[0], e[1] });
var p: Permissions = .{}; p.read = true; std.debug.print("{any}\n", .{p});}Output:
u18 goes up to 262143apples: 12.{ .read = true, .write = false, .delete = false }@Int(.unsigned, 18) is the same type as u18, but the bit count could come from a calculation. @Tuple takes a list of field types. @Struct takes the layout (.auto is a normal struct), an optional backing integer (only for packed structs), the field names, their types and their attributes. Here every field is a bool defaulting to false, so Flags(&.{ "read", "write", "delete" }) writes the struct for you. If this feels like a lot, that’s fine: it’s an advanced tool, and you can come back to it.
Changed or removed in 0.17
Section titled “Changed or removed in 0.17”If you copy older Zig code, these are the builtins most likely to trip you up:
| Old | Status in 0.17.1 | Use instead |
|---|---|---|
@Type(...) |
Removed: “invalid builtin function” | @Int, @Struct, @Enum, @Union, @Tuple, @Pointer, @Fn |
@cImport |
Removed | The build system and the translate-c package (see Zig C Interop) |
@intFromEnum, @enumFromInt |
Deprecated (still compiles) | @backingInt, @fromBackingInt |
@intFromFloat |
Deprecated (still compiles) | @trunc, @round, @floor, @ceil with an integer result type |
@hasDecl on a non-pub decl |
Now returns false |
Make the declaration pub |
Here’s what the first one looks like:
const U8 = @Type(.{ .int = .{ .signedness = .unsigned, .bits = 8 } });
pub fn main() void { const x: U8 = 1; _ = x;}main.zig:1:12: error: invalid builtin function: '@Type'const U8 = @Type(.{ .int = .{ .signedness = .unsigned, .bits = 8 } }); ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~The fix here is just @Int(.unsigned, 8), or plain u8.
Practice
Section titled “Practice”1. Clock arithmetic
Section titled “1. Clock arithmetic”It’s 3 o’clock. What time was it 5 hours ago, on a 24-hour clock? Compute it with const hour: i32 = 3; so that the answer is 22, not -2. Print both @rem and @mod to see the difference.
Hint: @mod(hour - 5, 24).
Show solution
const std = @import("std");
pub fn main() void { const hour: i32 = 3; std.debug.print("@rem: {d}\n", .{@rem(hour - 5, 24)}); std.debug.print("@mod: {d}\n", .{@mod(hour - 5, 24)});}Output:
@rem: -2@mod: 22@rem keeps the sign of hour - 5, which is negative. @mod always lands between 0 and 23 for a positive divisor, which is what wrap-around math like clocks and circular buffers needs.
2. Add without crashing
Section titled “2. Add without crashing”Write safeAdd(a: u8, b: u8) ?u8 that returns the sum, or null if it doesn’t fit in a u8. Print the result for 100 + 50 and 200 + 100.
Hint: const r = @addWithOverflow(a, b); then check r[1]. Print optionals with {?d}.
Show solution
const std = @import("std");
fn safeAdd(a: u8, b: u8) ?u8 { const r = @addWithOverflow(a, b); if (r[1] == 1) return null; return r[0];}
pub fn main() void { std.debug.print("{?d}\n", .{safeAdd(100, 50)}); std.debug.print("{?d}\n", .{safeAdd(200, 100)});}Output:
150nullA plain a + b would panic in a debug build when it overflows. @addWithOverflow hands you the decision instead. (std.math.add(u8, a, b) does the same and returns an error, if you prefer that.)
3. Powers of two
Section titled “3. Powers of two”A number is a power of two (1, 2, 4, 8…) when exactly one of its bits is set. Write isPowerOfTwo(x: u32) bool with a builtin, and test it on 1, 6, 64 and 0.
Hint: count the 1 bits.
Show solution
const std = @import("std");
fn isPowerOfTwo(x: u32) bool { return @popCount(x) == 1;}
pub fn main() void { for ([_]u32{ 1, 6, 64, 0 }) |x| { std.debug.print("{d}: {}\n", .{ x, isPowerOfTwo(x) }); }}Output:
1: true6: false64: true0: false6 is 0b110, two bits, so it’s not a power of two. 0 has no bits set at all, so it’s correctly false. The CPU usually has a single instruction for counting bits, and @popCount uses it.
- Everything starting with
@is built into the compiler and needs no import. - Casts like
@intCasttake their target from the result type: the variable’s type, or@as(T, ...). - Signed division needs
@divTrunc,@divFloor,@divCeil(new in 0.17) or@divExact; use@modfor wrap-around math. @addWithOverflowand friends report overflow instead of panicking.@import("builtin")has build facts likebuiltin.optimize(the build mode) andbuiltin.target.os.tag;@embedFileputs a file into your program.@Typeand@cImportare gone in 0.17; type-making builtins are now@Int,@Struct,@Enum, … and enums convert with@backingInt.
Next up: Zig Vectors (SIMD), for doing the same math on many numbers at once.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: Builtin Functions: every builtin with its signature and an example, in one long list.
- Zig 0.17.0 release notes: Language Changes:
@backingInt,@divCeil,@bitCastchanges and the@hasDeclrule. - Zig language reference: Type Coercion: when you need a cast builtin and when Zig converts for you.
- Zig language reference: Result Types: the rule behind casts that take their type from the left side.