Functions

Let’s look at defining our own functions in Zig:

const std = @import("std");
const print = std.debug.print;

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

// 'void' means there’s no return value.
fn output(n: u64) void {
    print("{}\n", .{n});
}

// A function can call itself.
fn factorial(n: u64) u64 {
    if (n == 0)
        return 1;
    return n * factorial(n - 1);
}

// 'pub fn' means the function is public, and can be
// used from outside the current module. 'main' is
// always public.
pub fn main() void {
    const a = add(1, 2);
    output(a);
    const b = factorial(5);
    output(b);
}
$ zig run functions.zig
3
120

Next example: Errors.