🎓 A1Learner
🔍
0 of 55 lessons completed

Zig Functions

A function is a named block of code that does one job. You write it once and call it by name whenever that job is needed.

Define and call a function

This function prints one word when it runs. Main calls it by name, and try passes on any error from printing.

const std = @import("std");

fn sayReady() !void {
    const out = std.io.getStdOut().writer();
    try out.print("Ready\n", .{});
}

pub fn main() !void {
    try sayReady();
}

A function can send a value back

This function sends back the number 7. Main stores the returned value and prints it.

const std = @import("std");

fn luckyNumber() i32 {
    return 7;
}

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const n = luckyNumber();
    try out.print("{d}\n", .{n});
}

Call the same function twice

Each call runs the function again from the top. Two calls print the line two times.

const std = @import("std");

fn printLine() !void {
    const out = std.io.getStdOut().writer();
    try out.print("---\n", .{});
}

pub fn main() !void {
    try printLine();
    try printLine();
}

Example

const std = @import("std");

fn printStart() !void {
    const out = std.io.getStdOut().writer();
    try out.print("Start\n", .{});
}

fn targetScore() i32 {
    return 80;
}

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    try printStart();
    const goal = targetScore();
    try out.print("Goal: {d}\n", .{goal});
    try printStart();
}

Key points

  • Define: the fn keyword starts a function, followed by the name you choose for it.
  • Call: writing the function's name with parentheses runs its code.
  • Return type: the type written after the parentheses names what the function sends back, or void when it sends nothing.
  • Return: the return keyword sends a value back to the code that called the function.
  • Reuse: one function can be called many times, from many places in a program.

In this example, printStart prints a word and sends nothing back, so its return type is !void. The targetScore function sends back 80, and main stores that value in goal. Main prints the goal, then calls printStart a second time.

Note

Zig reads the whole file first, so a function can be defined below the main function that calls it.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does the line `try greet();` do inside main?