TExcelTAD
Home › Zig › Zig Functions

Zig Functions

A function is a named piece of code you can call with inputs (parameters) and that can hand back an output (the return value). Zig functions are simple and explicit: every parameter has a type, the return type is always written, and parameters are constants inside the function.

Defining and calling functions

zig · try it yourself
const std = @import("std");

fn greet(name: []const u8) void {
    std.debug.print("Hello, {s}!\n", .{name});
}

fn add(a: i32, b: i32) i32 {
    return a + b;
}

pub fn main() void {
    greet("Linh");
    greet("Omar");
    const total = add(19, 23);
    std.debug.print("19 + 23 = {d}\n", .{total});
}
Hello, Linh!
Hello, Omar!
19 + 23 = 42
Part Meaning
fn starts a function declaration
add the name (camelCase by convention)
(a: i32, b: i32) parameters with their types
i32 after ) the return type (void = nothing)
pub makes the function visible to other files

Functions can be declared in any order at the top level, so main can call functions defined below it.

Return values must be used

If a function returns something, the caller must use it or explicitly discard it with _ =. Ignoring a result by accident is a compile error ("value of type 'i32' ignored"):

zig
add(1, 2);      // error: value of type 'i32' ignored
_ = add(1, 2);  // ok: deliberately discarded

Parameters are immutable

You cannot assign to a parameter. If you need a changing value, copy it into a local var:

zig · try it yourself
const std = @import("std");

fn countDigits(number: u64) u32 {
    var n = number; // local mutable copy
    var digits: u32 = 1;
    while (n >= 10) : (n /= 10) {
        digits += 1;
    }
    return digits;
}

pub fn main() void {
    const samples = [_]u64{ 7, 42, 1000, 9876543210 };
    for (samples) |s| {
        std.debug.print("{d} has {d} digit(s)\n", .{ s, countDigits(s) });
    }
}
7 has 1 digit(s)
42 has 2 digit(s)
1000 has 4 digit(s)
9876543210 has 10 digit(s)

Note: Zig may pass large parameters (structs, arrays) by reference behind the scenes for speed. Because parameters are read-only, you can't tell the difference — so don't take a pointer just for performance. Take a pointer (*T) only when the function must modify the caller's value.

Returning several values

A function returns one value, but that value can be a struct or a tuple:

zig · try it yourself
const std = @import("std");

fn minMax(values: []const i32) struct { min: i32, max: i32 } {
    var lo = values[0];
    var hi = values[0];
    for (values[1..]) |v| {
        lo = @min(lo, v);
        hi = @max(hi, v);
    }
    return .{ .min = lo, .max = hi };
}

fn divmod(a: u32, b: u32) struct { u32, u32 } {
    return .{ a / b, a % b };
}

pub fn main() void {
    const r = minMax(&.{ 8, -3, 14, 0, 6 });
    std.debug.print("min={d} max={d}\n", .{ r.min, r.max });

    const q, const rem = divmod(47, 5);
    std.debug.print("47 / 5 = {d} remainder {d}\n", .{ q, rem });
}
min=-3 max=14
47 / 5 = 9 remainder 2

Recursion

A function can call itself. Each call gets its own copy of its parameters on the stack:

zig · try it yourself
const std = @import("std");

fn factorial(n: u64) u64 {
    if (n <= 1) return 1;
    return n * factorial(n - 1);
}

fn sumDigits(n: u32) u32 {
    return if (n < 10) n else n % 10 + sumDigits(n / 10);
}

pub fn main() void {
    for (0..6) |i| std.debug.print("{d}! = {d}\n", .{ i, factorial(i) });
    std.debug.print("digit sum of 98765 = {d}\n", .{sumDigits(98765)});
}
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
digit sum of 98765 = 35

Deep recursion can overflow the stack, so for long sequences prefer a loop.

No overloading, no default arguments

Zig has no function overloading (two functions with the same name) and no default parameter values. Use different names (parseInt, parseFloat) or pass an options struct, a common Zig idiom:

zig
const Options = struct { width: u32 = 80, colour: bool = true };

fn render(text: []const u8, opts: Options) void { … }

render("hi", .{});               // all defaults
render("hi", .{ .width = 40 });  // override one field

Functions as values

Functions have types and can be passed around as values. A parameter of type *const fn (i32) i32 accepts any function with that signature:

zig
fn apply(f: *const fn (i32) i32, x: i32) i32 {
    return f(x);
}

Test yourself

What does fn area(w: u32, h: u32) u32 return?

  1. Nothing
  2. A u32
  3. Two values
  4. A pointer

What happens if you call a function that returns i32 and ignore the result?

  1. Nothing
  2. A warning
  3. Compile error: value ignored
  4. The value is printed

Can a function assign a new value to one of its parameters?

  1. Yes, always
  2. No, parameters are constants
  3. Only for integers
  4. Only if marked var