Zig Function Parameters
In the last lesson you wrote functions that take a few numbers and return a result. Now it’s time to look closer at the inputs. What happens to a value when you pass it in? Can a function change your variable? And how do you write one function that works for several types? Zig’s answers are simple and strict, and once you know them you’ll be able to tell what a function does to your data just from its signature.
Parameters are constants
Section titled “Parameters are constants”Inside a function, every parameter acts like a const. You can read it, but you can’t assign to it:
fn double(x: i32) i32 { x = x * 2; return x;}
pub fn main() void { _ = double(3);}main.zig:2:5: error: cannot assign to constant x = x * 2; ^In C, JavaScript or Python you can reuse a parameter as a scratch variable. Zig says no, so a parameter always holds what the caller passed, from the first line of the function to the last. If you do need a value that changes, copy it into a var:
const std = @import("std");
fn countDown(from: u32) void { var n = from; while (n > 0) : (n -= 1) { std.debug.print("{d}... ", .{n}); } std.debug.print("liftoff!\n", .{});}
pub fn main() void { countDown(3);}Output:
3... 2... 1... liftoff!var n = from; makes a local copy you’re free to change. That one extra line also tells the reader “this number is going to count down”.
Passing by value: the function gets a copy
Section titled “Passing by value: the function gets a copy”When you pass a number, a bool or even a whole array, the function works with its own copy. Changing the copy doesn’t touch the original:
const std = @import("std");
fn tryChange(arr: [3]i32) void { var copy = arr; copy[0] = 100; std.debug.print("inside: {any}\n", .{copy});}
pub fn main() void { const scores = [_]i32{ 3, 5, 7 }; tryChange(scores); std.debug.print("outside: {any}\n", .{scores});}Output:
inside: { 100, 5, 7 }outside: { 3, 5, 7 }This is called passing by value. You can always tell what a call can do to your data: if you pass a plain value like scores, the function can’t change your variable. Arrays get their own lesson in Zig Arrays.
Changing the caller’s variable with a pointer
Section titled “Changing the caller’s variable with a pointer”Sometimes changing the caller’s data is the whole point. For that, the function takes a pointer: the address of the variable, instead of a copy of its value. You’ll learn pointers properly in Zig Pointers, but three pieces are enough for now:
*i32is the type “pointer to ani32”.&scoregives you the address ofscore.score.*means “the value the pointer points at”, and you can assign to it.
const std = @import("std");
fn addBonus(score: *i32, bonus: i32) void { score.* += bonus;}
pub fn main() void { var score: i32 = 10; addBonus(&score, 5); addBonus(&score, 20); std.debug.print("score: {d}\n", .{score});}Output:
score: 35The parameter score itself is still a constant: it always points at the same variable. What changes is the value it points at. The & at the call site is the nice part: anyone reading addBonus(&score, 5) can see right away that score might change.
Forget the &, and Zig tells you exactly what’s wrong:
const std = @import("std");
fn reset(score: *i32) void { score.* = 0;}
pub fn main() void { var score: i32 = 10; reset(score); std.debug.print("{d}\n", .{score});}main.zig:8:9: error: local variable is never mutated var score: i32 = 10; ^~~~~main.zig:8:9: note: consider using 'const'main.zig:9:11: error: expected type '*i32', found 'i32' reset(score); ^~~~~You get two errors for one mistake. Without the &, nothing could ever change score, so Zig also complains that it should be a const. When you see both errors together, a missing & is the usual cause.
You also can’t hand out a changeable pointer to a const:
const std = @import("std");
fn addBonus(score: *i32, bonus: i32) void { score.* += bonus;}
pub fn main() void { const score: i32 = 10; addBonus(&score, 5); std.debug.print("score: {d}\n", .{score});}main.zig:9:14: error: expected type '*i32', found '*const i32' addBonus(&score, 5); ^~~~~~main.zig:9:14: note: cast discards const qualifier& on a const gives a *const i32, a pointer you can only read through. Make the variable a var if the function is meant to change it.
Slices: passing a list of values
Section titled “Slices: passing a list of values”To give a function a list of items, use a slice parameter. []const i32 means “some i32 values in a row that I’ll only read”, and []i32 means “…that I may change”. You make one from an array with &:
const std = @import("std");
fn total(numbers: []const i32) i32 { var sum: i32 = 0; for (numbers) |n| sum += n; return sum;}
fn doubleAll(numbers: []i32) void { for (numbers) |*n| n.* *= 2;}
pub fn main() void { var scores = [_]i32{ 3, 5, 7 }; std.debug.print("total: {d}\n", .{total(&scores)}); doubleAll(&scores); std.debug.print("doubled: {any}\n", .{scores}); std.debug.print("total: {d}\n", .{total(&scores)});}Output:
total: 15doubled: { 6, 10, 14 }total: 30The slice doesn’t copy the items. It points at the caller’s array, which is how doubleAll can change them. In the loop, |*n| captures a pointer to each item, so n.* *= 2 changes the item itself. A slice also works for any length: total doesn’t care whether the array has 3 items or 3,000. Slices get a full lesson in Zig Slices.
anytype: one function, many types
Section titled “anytype: one function, many types”Zig has no overloading, but a parameter can have the type anytype. Then Zig works out the real type at each call:
const std = @import("std");
fn describe(value: anytype) void { std.debug.print("{any} is a {s}\n", .{ value, @typeName(@TypeOf(value)) });}
pub fn main() void { describe(@as(i32, 7)); describe(@as(f64, 2.5)); describe(true);}Output:
7 is a i322.5 is a f64true is a bool@TypeOf(value) gives the type of the value, and @typeName turns a type into text. @as(i32, 7) just gives the number 7 a clear type. Behind the scenes, Zig makes a separate copy of describe for each type it’s called with, so there’s no slowdown at run time.
You can use @TypeOf in the return type too, to return the same type you got:
const std = @import("std");
fn addOne(x: anytype) @TypeOf(x) { return x + 1;}
pub fn main() void { const small: u8 = 41; const big: i64 = 999; std.debug.print("{d} {d}\n", .{ addOne(small), addOne(big) });}Output:
42 1000The catch: anytype accepts anything at the call, and the error only shows up inside the function. Pass a bool to addOne:
fn addOne(x: anytype) @TypeOf(x) { return x + 1;}
pub fn main() void { _ = addOne(true);}main.zig:2:14: error: incompatible types: 'bool' and 'comptime_int' return x + 1; ~~^~~main.zig:2:12: note: type 'bool' here return x + 1; ^main.zig:2:16: note: type 'comptime_int' here return x + 1; ^The error points at x + 1 inside addOne, not at your call, which can be confusing in a big function. That’s why anytype is best for small helpers. The reference on parameter type inference has the official rules.
Passing a type as a parameter
Section titled “Passing a type as a parameter”There’s a more explicit way to write a function for many types: take the type itself as the first parameter. Types are values in Zig, but they only exist while compiling, so the parameter is marked comptime:
const std = @import("std");
fn maxOf(comptime T: type, a: T, b: T) T { return if (a > b) a else b;}
pub fn main() void { std.debug.print("{d}\n", .{maxOf(u8, 3, 9)}); std.debug.print("{d}\n", .{maxOf(f32, 2.5, -1.0)});}Output:
92.5comptime T: type means “a type, known at compile time”. Then a: T, b: T says both numbers have that same type, which anytype can’t express. You’ve already used functions like this: std.mem.eql(u8, a, b) takes u8 as its first argument for the same reason. This is the start of generics, which get a full section later in Zig Generics.
Practice
Section titled “Practice”1. Swap two numbers
Section titled “1. Swap two numbers”Write swap(a: *i32, b: *i32) void that swaps two variables, so after swap(&x, &y) with x = 1 and y = 2, x is 2 and y is 1.
Hint: save a.* in a const first, then copy b.* into a.*, then the saved value into b.*.
Show solution
const std = @import("std");
fn swap(a: *i32, b: *i32) void { const old_a = a.*; a.* = b.*; b.* = old_a;}
pub fn main() void { var x: i32 = 1; var y: i32 = 2; swap(&x, &y); std.debug.print("x = {d}, y = {d}\n", .{ x, y });}Output:
x = 2, y = 1Without pointers, swap would only swap its own copies and x and y would stay the same. The standard library has this as std.mem.swap(i32, &x, &y).
2. Count the hot days
Section titled “2. Count the hot days”Write countAbove(values: []const i32, limit: i32) usize that returns how many values are bigger than limit. Use it on the temperatures { 18, 25, 31, 22, 29 } with a limit of 24.
Hint: start a var count: usize = 0; and add 1 inside a for loop.
Show solution
const std = @import("std");
fn countAbove(values: []const i32, limit: i32) usize { var count: usize = 0; for (values) |v| { if (v > limit) count += 1; } return count;}
pub fn main() void { const temps = [_]i32{ 18, 25, 31, 22, 29 }; std.debug.print("hot days: {d}\n", .{countAbove(&temps, 24)});}Output:
hot days: 3[]const i32 is the right type here: the function only reads the values, and the caller’s array can even be a const.
3. Cap the scores
Section titled “3. Cap the scores”Write capAll(scores: []i32, max: i32) void that lowers every score above max to max, in place. Try it with { 40, 120, 85, 300 } and a max of 100.
Hint: loop with |*s| so you get a pointer to each item, and assign to s.*.
Show solution
const std = @import("std");
fn capAll(scores: []i32, max: i32) void { for (scores) |*s| { if (s.* > max) s.* = max; }}
pub fn main() void { var scores = [_]i32{ 40, 120, 85, 300 }; capAll(&scores, 100); std.debug.print("{any}\n", .{scores});}Output:
{ 40, 100, 85, 100 }The parameter is []i32 (no const), because the function changes the items. The array in main has to be a var for the same reason.
- Parameters are constants: copy one into a
varif you need to change it. - Values are passed by value: the function sees a copy, even for arrays (Zig may use a hidden reference for speed, but it behaves like a copy).
- To change the caller’s variable, take a pointer (
*i32), call with&x, and write throughx.*. - Use slices for lists:
[]const Tto read,[]Tto change the items. anytypelets one function accept many types, and@TypeOftells you which one you got.comptime T: typepasses a type explicitly, so several parameters can share it.
Next up: Zig Scope, where a name lives, why Zig won’t let you reuse one, and variables that live for the whole program.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: Pass-by-value Parameters: how Zig passes structs and arrays, and why parameters are immutable.
- Zig language reference: Function Parameter Type Inference: the official rules for
anytype. - Zig language reference: Compile-Time Parameters:
comptimeparameters and types as values. - Zig language reference: Pointers: every kind of pointer, for when you want the details now.