Learn/Zig/6. Functions
Lesson 6 of 8
Sign in

Zig, lesson 6

Functions

As a program grows, you want to give a piece of logic a name, reuse it, and test it on its own. In Zig that is a function, declared with fn.

Declaring a function

Every parameter has a type, and the return type comes after the parentheses. Unlike some languages, Zig needs an explicit return; the last expression is not returned automatically. Functions are usually declared at the top level of the file, outside main, and can appear before or after the code that calls them.

Function names use camelCase: isPrime, printReceipt. Add pub in front (pub fn) when other files should be able to call it; for a one-file program you only need it on .

2 exercises to try what you just read.

Exercise 1

Prime checker

Press Ctrl Enter or Check to test your code.

Exercise 2

Volume knob

Press Ctrl Enter or Check to test your code.

main

Parameters are constants

Inside the function, parameters cannot be changed. If you need a changing value, copy it into a var:

And, as with local variables, an unused parameter is a compile error. Write _ = name; while a function is still unfinished.

Functions that can fail

A function that might fail returns an error union: !T means "either an error or a T". You create an error with error.SomeName, and the caller handles it with try, which hands the error up to its own caller:

in has the type *std.Io.Reader, a pointer to the reader interface you set up in main. This little helper saves you three lines every time you read a number, and you will use it from now on. If main receives an error through try, the program stops and prints the error name, which is far better than carrying on with bad data.

Scope: what a function can see

A function sees its parameters, its own locals, and anything declared at the top level of the file, such as std or a const vat_rate = 20;. It cannot see the local variables of main or any other function. If a function needs a value, pass it in as a parameter. That keeps every function self-contained: you can understand it by reading it alone.

Further reading

  • Zig Language Reference: Functions
  • Zig Language Reference: Errors
  • Zig Language Reference: try

Write fn isPrime(n: i64) bool, which returns true when a number is prime (it has exactly two divisors, 1 and itself) and false otherwise. Numbers below 2 are not prime.

Try divisors d = 2, 3, 4, ... while d * d <= n, and return false as soon as one divides n evenly. Both values are positive there, so @rem(n, d) (or @mod) gives the remainder.

Input: one whole number. Output: N is prime or N is not prime.

prints 97 is prime.

A speaker's volume must stay between a lowest and a highest setting. Write fn clamp(value: i64, low: i64, high: i64) i64, which returns:

  • low if the value is below low,
  • high if the value is above high,
  • the value itself otherwise.

Input: three lines: the requested value, then low, then high (low is never above high). Output: the clamped value.

fn total(price: u32, quantity: u32) u32 {
    return price * quantity;
}
fn countDigits(n: u64) u32 {
    var rest = n;
    var digits: u32 = 1;
    while (rest >= 10) : (rest /= 10) {
        digits += 1;
    }
    return digits;
}
fn readInt(in: *std.Io.Reader) !i64 {
    const line = (try in.takeDelimiter('\n')) orelse return error.EndOfStream;
    return std.fmt.parseInt(i64, std.mem.trim(u8, line, " \t\r"), 10);
}

// in main:
const age = try readInt(in);
97