Zig Function Pointers
Sometimes you want to tell a function what to do, not just what to work on: “sort these, and here’s how to compare them”, or “run this for every item”. To do that, you pass one function to another. In Zig you do it with a function pointer. This lesson shows how, and then deals with the big difference from JavaScript, Python or Rust: Zig has no closures, so you’ll learn the pattern Zig code uses instead.
Passing a function to a function
Section titled “Passing a function to a function”Here applyToAll takes a list of numbers and a function, and runs the function on every number:
const std = @import("std");
fn applyToAll(numbers: []i32, f: *const fn (i32) i32) void { for (numbers) |*n| n.* = f(n.*);}
fn double(x: i32) i32 { return x * 2;}
fn negate(x: i32) i32 { return -x;}
pub fn main() void { var numbers = [_]i32{ 1, 2, 3 }; applyToAll(&numbers, double); std.debug.print("{any}\n", .{numbers}); applyToAll(&numbers, negate); std.debug.print("{any}\n", .{numbers});}Output:
{ 2, 4, 6 }{ -2, -4, -6 }The parameter type *const fn (i32) i32 reads as “a pointer to a function that takes an i32 and returns an i32”. To pass a function, write its name without parentheses: double, not double(). Inside, you call f(n.*) like any other function.
Function types and function pointers
Section titled “Function types and function pointers”Zig has two related types here, and the difference matters once:
const std = @import("std");
fn add(a: i32, b: i32) i32 { return a + b;}
pub fn main() void { std.debug.print("{}\n", .{@TypeOf(add)}); std.debug.print("{}\n", .{@TypeOf(&add)});}Output:
fn (i32, i32) i32*const fn (i32, i32) i32fn (i32, i32) i32 is the function itself: its code. That only exists while compiling, so you can’t store it in a var. *const fn (i32, i32) i32 is a pointer to the function’s code, an ordinary value that can be stored, passed around and changed while the program runs. When a function name is used where a function pointer is expected, Zig takes the address for you, which is why applyToAll(&numbers, double) didn’t need an &.
Try to store the function itself in a var, and the compiler even tells you the fix:
const std = @import("std");
fn add(a: i32, b: i32) i32 { return a + b;}
fn sub(a: i32, b: i32) i32 { return a - b;}
pub fn main() void { var op = add; if (std.debug.runtime_safety) op = sub; std.debug.print("{d}\n", .{op(5, 3)});}main.zig:12:9: error: variable of type 'fn (i32, i32) i32' must be const or comptime var op = add; ^~main.zig:12:9: note: use '*const fn (i32, i32) i32' for a function pointer typeThe reference’s Functions section shows the same idea in its doOp example.
Picking a function while the program runs
Section titled “Picking a function while the program runs”With a function pointer type, you can decide which function to call at run time. A small calculator picks the operation from a symbol:
const std = @import("std");
const Op = *const fn (i32, i32) i32;
fn add(a: i32, b: i32) i32 { return a + b;}
fn sub(a: i32, b: i32) i32 { return a - b;}
fn mul(a: i32, b: i32) i32 { return a * b;}
fn pick(symbol: u8) Op { return switch (symbol) { '+' => add, '-' => sub, else => mul, };}
pub fn main() void { const symbols = "+-*"; for (symbols) |s| { const op = pick(s); std.debug.print("6 {c} 3 = {d}\n", .{ s, op(6, 3) }); }}Output:
6 + 3 = 96 - 3 = 36 * 3 = 18const Op = *const fn (i32, i32) i32; gives the long type a short name, which makes the rest of the code easier to read. pick returns a function, and op(6, 3) calls whichever one it got.
You can also keep functions in an array, which makes a handy lookup table:
const std = @import("std");
const Op = *const fn (i32, i32) i32;
fn add(a: i32, b: i32) i32 { return a + b;}
fn mul(a: i32, b: i32) i32 { return a * b;}
pub fn main() void { const ops = [_]Op{ add, mul }; const names = [_][]const u8{ "add", "mul" }; for (ops, names) |op, name| { std.debug.print("{s}(6, 3) = {d}\n", .{ name, op(6, 3) }); }}Output:
add(6, 3) = 9mul(6, 3) = 18The signature has to match exactly
Section titled “The signature has to match exactly”A function pointer type includes the number and types of the parameters and the return type. A function with a different shape doesn’t fit:
const std = @import("std");
fn add(a: i32, b: i32) i32 { return a + b;}
fn apply(f: *const fn (i32) i32, x: i32) i32 { return f(x);}
pub fn main() void { std.debug.print("{d}\n", .{apply(add, 3)});}main.zig:12:38: error: expected type '*const fn (i32) i32', found '*const fn (i32, i32) i32' std.debug.print("{d}\n", .{apply(add, 3)}); ^~~main.zig:12:38: note: pointer type child 'fn (i32, i32) i32' cannot cast into pointer type child 'fn (i32) i32'main.zig:12:38: note: function with 2 parameters cannot cast into a function with 1 parametersThat’s a good thing: a mismatch here is caught while compiling, not as a crash later.
A quick function without a name
Section titled “A quick function without a name”Zig has no lambdas or arrow functions. Writing fn (x: i32) i32 { ... } in the middle of an expression is a syntax error. But you can declare a function inside an unnamed struct and use it right there:
const std = @import("std");
fn applyToAll(numbers: []i32, f: *const fn (i32) i32) void { for (numbers) |*n| n.* = f(n.*);}
pub fn main() void { var numbers = [_]i32{ 1, 2, 3 }; applyToAll(&numbers, struct { fn addTen(x: i32) i32 { return x + 10; } }.addTen); std.debug.print("{any}\n", .{numbers});}Output:
{ 11, 12, 13 }struct { fn addTen(...) ... } makes a struct type with one function in it, and .addTen picks that function. It looks a bit odd at first, but you’ll see it in real Zig code (and in the standard library’s tests) whenever a one-off function is needed. If you need it twice, give it a normal name at the top level instead.
Zig has no closures
Section titled “Zig has no closures”In JavaScript, a function can use variables from around it:
const bonus = getBonus();scores.map((s) => s + bonus); // uses `bonus` from outsideThat’s a closure: the function carries a bit of its surroundings with it. Zig functions can’t do that. A function inside a struct can only use things known at compile time from outside, not your runtime variables:
const std = @import("std");
pub fn main() void { var bonus: i32 = 5; bonus += 1; const Helper = struct { fn addBonus(x: i32) i32 { return x + bonus; } }; std.debug.print("{d}\n", .{Helper.addBonus(1)});}main.zig:8:24: error: mutable 'bonus' not accessible from here return x + bonus; ^~~~~main.zig:4:9: note: declared mutable here var bonus: i32 = 5; ^~~~~main.zig:6:20: note: crosses namespace boundary here const Helper = struct { ^~~~~~Why? A closure needs somewhere to keep the captured variables, and that usually means a hidden memory allocation. Zig’s rule is that nothing allocates memory behind your back, so it leaves closures out and makes you pass the data yourself. That sounds like a loss, but the pattern for it is short.
Instead of a closure: pass a context
Section titled “Instead of a closure: pass a context”The Zig way is to pass the extra data as a separate argument, usually called the context, together with a function that takes it. You’ve already got a real example in the standard library: std.mem.sort takes a context and a compare function.
const std = @import("std");
const ByDistance = struct { target: i32,
fn lessThan(self: ByDistance, a: i32, b: i32) bool { return @abs(a - self.target) < @abs(b - self.target); }};
pub fn main() void { var numbers = [_]i32{ 3, 15, 9, 22, 11 };
std.mem.sort(i32, &numbers, {}, std.sort.asc(i32)); std.debug.print("smallest first: {any}\n", .{numbers});
const target: i32 = 10; std.mem.sort(i32, &numbers, ByDistance{ .target = target }, ByDistance.lessThan); std.debug.print("closest to {d} first: {any}\n", .{ target, numbers });}Output:
smallest first: { 3, 9, 11, 15, 22 }closest to 10 first: { 9, 11, 15, 3, 22 }The first sort needs no extra data, so the context is {} (an empty value) and std.sort.asc(i32) is a ready-made “smaller first” function. The second sort needs to know the target, so we put it in a struct, ByDistance{ .target = target }, and pass that as the context. std.mem.sort hands the context to lessThan as its first argument every time it compares two numbers. The struct plays the role of the closure’s captured variables, but you can see exactly where it lives.
You can write your own functions in the same style. Here forEach takes any context plus a function that accepts it:
const std = @import("std");
fn forEach(numbers: []const i32, context: anytype, comptime f: fn (@TypeOf(context), i32) void) void { for (numbers) |n| f(context, n);}
const Summer = struct { total: i32 = 0, count: u32 = 0,
fn add(self: *Summer, n: i32) void { self.total += n; self.count += 1; }};
pub fn main() void { const numbers = [_]i32{ 4, 8, 15, 16, 23, 42 }; var summer = Summer{}; forEach(&numbers, &summer, Summer.add); std.debug.print("{d} numbers, total {d}\n", .{ summer.count, summer.total });}Output:
6 numbers, total 108The context here is &summer, a pointer, so Summer.add can change it, and when forEach is done, the results are sitting in summer. Structs with functions inside are covered in Zig Struct Methods; for now, notice the shape: the data and the function travel together, side by side.
Zig’s allocator interface, which you’ll meet in Zig Allocators, is the runtime version of this pattern: a pointer to some data plus a table of function pointers. That’s how one std.mem.Allocator value can stand for many kinds of allocators.
Practice
Section titled “Practice”1. Apply twice
Section titled “1. Apply twice”Write applyTwice(f: *const fn (i32) i32, x: i32) i32 that returns f(f(x)). Try it with a function addThree on 10, and with square on 3.
Hint: pass the function names without parentheses.
Show solution
const std = @import("std");
fn applyTwice(f: *const fn (i32) i32, x: i32) i32 { return f(f(x));}
fn addThree(x: i32) i32 { return x + 3;}
fn square(x: i32) i32 { return x * x;}
pub fn main() void { std.debug.print("{d}\n", .{applyTwice(addThree, 10)}); std.debug.print("{d}\n", .{applyTwice(square, 3)});}Output:
168110 + 3 + 3 is 16, and (3 × 3) squared is 81.
2. Biggest first
Section titled “2. Biggest first”Sort { 5, 1, 4, 2, 3 } from biggest to smallest with std.mem.sort.
Hint: next to std.sort.asc, there’s a std.sort.desc. The context is still {}.
Show solution
const std = @import("std");
pub fn main() void { var numbers = [_]i32{ 5, 1, 4, 2, 3 }; std.mem.sort(i32, &numbers, {}, std.sort.desc(i32)); std.debug.print("{any}\n", .{numbers});}Output:
{ 5, 4, 3, 2, 1 }std.sort.desc(i32) is a function that returns a compare function, built for the type you give it.
3. Count with a context
Section titled “3. Count with a context”Write countIf(numbers: []const i32, context: anytype, comptime pred: fn (@TypeOf(context), i32) bool) usize. Then use it with a context struct AtLeast that has a min field, to count how many of { 3, 10, 7, 12, 1 } are at least 7.
Hint: give AtLeast a function check(self: AtLeast, n: i32) bool and pass AtLeast{ .min = 7 } and AtLeast.check.
Show solution
const std = @import("std");
fn countIf(numbers: []const i32, context: anytype, comptime pred: fn (@TypeOf(context), i32) bool) usize { var count: usize = 0; for (numbers) |n| { if (pred(context, n)) count += 1; } return count;}
const AtLeast = struct { min: i32,
fn check(self: AtLeast, n: i32) bool { return n >= self.min; }};
pub fn main() void { const numbers = [_]i32{ 3, 10, 7, 12, 1 }; const result = countIf(&numbers, AtLeast{ .min = 7 }, AtLeast.check); std.debug.print("{d} numbers are at least 7\n", .{result});}Output:
3 numbers are at least 7AtLeast{ .min = 7 } is the data a closure would have captured. Change it to .min = 10 and the same countIf gives 2.
- A function pointer type looks like
*const fn (i32) i32: parameter types, then the return type. - Pass a function by its name without parentheses; Zig takes its address for you.
fn (...) Tis the function itself (compile time only);*const fn (...) Tcan be stored in variables and arrays and chosen at run time.- The signature must match exactly, or the build fails.
- For a one-off function, declare it in an unnamed struct:
struct { fn f(...) ... }.f. - Zig has no closures. Pass the extra data as a context argument next to the function, like
std.mem.sortdoes.
Next up: Zig Inline Functions, inline fn and inline for, and the few times you actually need them.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: Functions: function declarations and the
*const fnpointer type, with thedoOpexample. - Zig language reference: Compile-Time Parameters: why
comptime f: fn ...makes a copy of the function for each callback. - Zig language reference: Function Parameter Type Inference: how
anytypecontexts work. - Zig in-depth overview: the “no hidden allocations” rule that explains why there are no closures.