Zig Inline Functions
The word inline shows up in two places in Zig: on functions (inline fn) and on loops (inline for). If you know C or C++, you might think it’s a speed hint. In Zig it isn’t. It changes how the code is compiled, and the main reason to use it is to keep values known at compile time. This is a short lesson, because the honest advice is: you’ll rarely write inline fn, but you’ll use inline for now and then, especially for loops over types.
inline fn
Section titled “inline fn”Put inline in front of fn, and Zig pastes the function’s body into every place that calls it, instead of making a real function call:
const std = @import("std");
inline fn square(x: i32) i32 { return x * x;}
pub fn main() void { std.debug.print("{d}\n", .{square(7)});}Output:
49For you as the caller, nothing changes: you call it like any function and get the same answer. The difference is in the machine code, where there’s no call to square, just the multiplication.
What inline fn really changes: compile-time values
Section titled “What inline fn really changes: compile-time values”The real effect of inline fn is this: when you pass values that are known at compile time, the result is known at compile time too. With a normal function call, it isn’t. You can see the difference when the result has to be known while compiling, like when you use it to pick a type:
const std = @import("std");
fn isBig(x: u32) bool { return x > 100;}
pub fn main() void { const T = if (isBig(500)) u64 else u8; std.debug.print("{s}\n", .{@typeName(T)});}main.zig:8:15: error: value with comptime-only type 'type' depends on runtime control flow const T = if (isBig(500)) u64 else u8; ^~~~~~~~~~~~~~~~~~~~~~~~~~~main.zig:8:24: note: runtime control flow here const T = if (isBig(500)) u64 else u8; ~~~~~^~~~~main.zig:8:15: note: types are not available at runtimeisBig(500) is a normal call, so Zig treats its result as something that will be worked out when the program runs. But types only exist while compiling, so it can’t choose between u64 and u8 based on a run-time answer. Now add inline:
const std = @import("std");
inline fn isBig(x: u32) bool { return x > 100;}
pub fn main() void { const T = if (isBig(500)) u64 else u8; std.debug.print("{s}\n", .{@typeName(T)});}Output:
u64Because the body is pasted in, Zig sees 500 > 100 directly, knows the answer is true while compiling, and picks u64.
You often don’t need inline for this, though. Putting comptime in front of the call asks Zig to run that one call at compile time, with a normal function:
const std = @import("std");
fn isBig(x: u32) bool { return x > 100;}
pub fn main() void { const T = if (comptime isBig(500)) u64 else u8; std.debug.print("{s}\n", .{@typeName(T)});}Output:
u64comptime isBig(500) is clearer about what you want, and isBig stays an ordinary function. inline fn is for when every call should pass compile-time values through, which mostly comes up in generic library code. Comptime gets its own lessons starting with Zig Comptime.
What you can’t do with an inline fn
Section titled “What you can’t do with an inline fn”Because an inline function never exists as a real function in the program, two things don’t work.
You can’t take a function pointer to it, since there’s no function to point at:
const std = @import("std");
inline fn double(x: i32) i32 { return x * 2;}
fn apply(f: *const fn (i32) i32, x: i32) i32 { return f(x);}
pub fn main() void { std.debug.print("{d}\n", .{apply(double, 3)});}main.zig:12:38: error: expected type '*const fn (i32) i32', found '*const fn (i32) callconv(.@"inline") i32' std.debug.print("{d}\n", .{apply(double, 3)}); ^~~~~~main.zig:12:38: note: pointer type child 'fn (i32) callconv(.@"inline") i32' cannot cast into pointer type child 'fn (i32) i32'main.zig:12:38: note: calling convention 'inline' cannot cast into calling convention 'auto'And it can’t call itself with a run-time value, because pasting the body into itself would never end:
const std = @import("std");
inline fn factorial(n: u32) u32 { if (n <= 1) return 1; return n * factorial(n - 1);}
pub fn main() void { var n: u32 = 5; n += 0; std.debug.print("{d}\n", .{factorial(n)});}main.zig:5:25: error: inline call is recursive return n * factorial(n - 1); ~~~~~~~~~^~~~~~~main.zig:11:41: note: called inline here std.debug.print("{d}\n", .{factorial(n)}); ~~~~~~~~~^~~Both are good reasons to leave inline off unless you have a specific need for it.
inline for: a loop that’s unrolled
Section titled “inline for: a loop that’s unrolled”A normal for loop is one piece of code that runs again and again. An inline for is unrolled: Zig copies the loop body once for every item, while compiling. That matters when each item can be different in a way that only exists at compile time. The classic case is a list of types:
const std = @import("std");
pub fn main() void { const types = [_]type{ u8, u16, u32, u64 }; for (types) |T| { std.debug.print("{s}: {d} bytes\n", .{ @typeName(T), @sizeOf(T) }); }}main.zig:5:10: error: values of type 'type' must be comptime-known, but index value is runtime-known for (types) |T| { ^~~~~main.zig:5:10: note: types are not available at runtimeA normal loop picks its item while the program runs, but types don’t exist then. Make it inline for, and each round is worked out while compiling:
const std = @import("std");
pub fn main() void { const types = [_]type{ u8, u16, u32, u64 }; inline for (types) |T| { std.debug.print("{s}: {d} bytes\n", .{ @typeName(T), @sizeOf(T) }); }}Output:
u8: 1 bytesu16: 2 bytesu32: 4 bytesu64: 8 bytesIt’s as if you had written the print line four times, once with each type filled in. The reference section on inline for has more examples.
Looping over values of different types
Section titled “Looping over values of different types”The other common case is a tuple: a group of values that can each have a different type, like .{ @as(u8, 200), @as(f32, 1.5), true }. A normal for can’t walk over it, because the type of thing would change from round to round:
const std = @import("std");
pub fn main() void { const things = .{ @as(u8, 200), @as(f32, 1.5), true }; for (things) |thing| { std.debug.print("{any}\n", .{thing}); }}main.zig:5:10: error: unable to resolve comptime value for (things) |thing| { ^~~~~~main.zig:5:10: note: tuple field index must be comptime-knownWith inline for, each copy of the body gets its own type:
const std = @import("std");
pub fn main() void { const things = .{ @as(u8, 200), @as(f32, 1.5), true }; inline for (things, 0..) |thing, i| { std.debug.print("{d}: {any} is a {s}\n", .{ i, thing, @typeName(@TypeOf(thing)) }); }}Output:
0: 200 is a u81: 1.5 is a f322: true is a boolYou’ll use this again in Zig Reflection, where inline for walks over the fields of a struct, each with its own name and type. There’s also an inline while, which works the same way for while loops.
Practice
Section titled “Practice”1. Bits per type
Section titled “1. Bits per type”Print how many bits each of these types has: i8, u16, f32, f64, bool. Use @bitSizeOf(T).
Hint: put the types in a [_]type{ ... } array and loop over it with inline for.
Show solution
const std = @import("std");
pub fn main() void { const types = [_]type{ i8, u16, f32, f64, bool }; inline for (types) |T| { std.debug.print("{s}: {d} bits\n", .{ @typeName(T), @bitSizeOf(T) }); }}Output:
i8: 8 bitsu16: 16 bitsf32: 32 bitsf64: 64 bitsbool: 1 bitsA bool needs only 1 bit of information, even though it takes a whole byte in memory (@sizeOf(bool) is 1).
2. Pick a type at compile time
Section titled “2. Pick a type at compile time”Write a normal (not inline) function needsBig(max: u64) bool that returns true when max is above 255. Use it to choose a Counter type: u16 for a max of 1000, and print its name.
Hint: without inline fn, you need comptime in front of the call.
Show solution
const std = @import("std");
fn needsBig(max: u64) bool { return max > 255;}
pub fn main() void { const Counter = if (comptime needsBig(1000)) u16 else u8; std.debug.print("{s}\n", .{@typeName(Counter)});}Output:
u16comptime needsBig(1000) runs the call while compiling, so the if can choose a type. Change 1000 to 200 and you get u8.
inline fnforces the function body to be pasted into every call. It’s an order, not a hint.- Its real effect: compile-time-known arguments give a compile-time-known result.
- Often
comptime f(x)on one call is the clearer choice. - You can’t take a function pointer to an inline function, and it can’t recurse with run-time values.
inline forunrolls a loop while compiling, so it can loop over types and tuples.- Let the compiler decide about speed. Use
inlinewhen you need compile-time values, not as an optimization.
Next up: Zig Arrays, fixed-size lists of values, and the first step towards pointers and slices.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: inline fn: the official rules and the short list of good reasons to use it.
- Zig language reference: inline for: unrolled loops, with examples over types.
- Zig language reference: inline while: the same idea for
whileloops. - Zig language reference: Compile-Time Parameters: how compile-time values flow through function calls.