Function Basics (fn Keyword)
In Zig, functions are defined using the fn keyword. All parameter types and return types must be declared explicitly — type inference is not performed. Values are returned with return. This page covers the basics of defining functions, calling them, and working with return values.
Syntax
// -----------------------------------------------
// fn — function definition
// -----------------------------------------------
fn functionName(paramName: ParamType, ...) ReturnType {
// body
return value;
}
// Adding pub makes the function callable from other files (public function)
pub fn functionName(paramName: ParamType) ReturnType {
return value;
}
// Use void when the function has no return value
fn functionName() void {
// body only — return can be omitted
}
// Functions that may return an error use !ReturnType
fn functionName() !void {
try someOperation();
}
Syntax Overview
| Syntax / Keyword | Description |
|---|---|
fn name() Type { } | Defines a function. All parameter types and the return type must be explicitly declared. |
pub fn | Defines a public function. It can be called from other files or from main(). |
return value; | Ends the function and returns a value to the caller. |
void | A type that indicates no return value. return; can be omitted. |
!void / !Type | An error union type. Used for functions that may return an error. |
try expr | Propagates an error to the caller if the expression returns one. |
paramName: Type | Parameters are declared as a name–type pair. Multiple parameters are separated by commas. |
comptime | Marks a parameter whose value is known at compile time. Used in generic functions and similar contexts. |
Sample Code
function_basic.zig
// function_basic.zig — sample for fn (defining and calling functions)
// Uses Dragon Ball characters to demonstrate
// return types, parameters, and basic use of return
// Import the standard library
const std = @import("std");
// -----------------------------------------------
// Function with no parameters and no return value
// pub is added so it can be called from main()
// -----------------------------------------------
pub fn greetGoku() void {
// Get a writer for standard output and print
const stdout = std.io.getStdOut().writer();
// Use _ to discard the error from print() when ignoring it
stdout.print("Goku has appeared!\n", .{}) catch {};
}
// -----------------------------------------------
// Function with a parameter and a return value (returns an integer)
// Doubles the given power level and returns it
// -----------------------------------------------
pub fn doublePower(power: u32) u32 {
// Return the computed result to the caller
return power * 2;
}
// -----------------------------------------------
// Function that takes multiple parameters and returns their sum
// Combines the power levels of two characters
// -----------------------------------------------
pub fn combinedPower(power1: u32, power2: u32) u32 {
return power1 + power2;
}
// -----------------------------------------------
// Function that takes a string slice and an integer as parameters
// Prints a greeting message with the character's name and power level
// -----------------------------------------------
pub fn introduce(name: []const u8, power: u32) void {
const stdout = std.io.getStdOut().writer();
stdout.print("Name: {s} Power: {d}\n", .{ name, power }) catch {};
}
// -----------------------------------------------
// Function that returns an error union type
// Returns an error if the power level is 0
// -----------------------------------------------
const BattleError = error{ZeroPower};
pub fn checkPower(power: u32) BattleError!u32 {
// Return an error if power is 0
if (power == 0) {
return BattleError.ZeroPower;
}
return power;
}
// -----------------------------------------------
// Program entry point
// -----------------------------------------------
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
try stdout.print("=== Dragon Ball Function Demo ===\n\n", .{});
// 1. Call a function with no parameters and no return value
greetGoku();
try stdout.print("\n", .{});
// 2. Receive the return value and print it
// Double Vegeta's power level
const vegeta_base: u32 = 9500;
const vegeta_doubled = doublePower(vegeta_base);
try stdout.print("Vegeta's power: {d} -> doubled: {d}\n", .{ vegeta_base, vegeta_doubled });
// 3. Pass multiple arguments and get the combined total
// Calculate the combined power of Goku and Piccolo
const goku_power: u32 = 9000;
const piccolo_power: u32 = 3500;
const total = combinedPower(goku_power, piccolo_power);
try stdout.print("Goku({d}) + Piccolo({d}) = combined power: {d}\n\n", .{ goku_power, piccolo_power, total });
// 4. Pass a string and an integer to display character info
try stdout.print("--- Character List ---\n", .{});
introduce("Goku", 9000);
introduce("Vegeta", 9500);
introduce("Piccolo", 3500);
introduce("Trunks", 5000);
introduce("Frieza", 530000);
// 5. Call a function returning an error union type using try
// A valid power level returns the value normally
try stdout.print("\n--- Power Check with Error Handling ---\n", .{});
const frieza_power = checkPower(530000) catch |err| {
try stdout.print("Error: {}\n", .{err});
return;
};
try stdout.print("Frieza's power check OK: {d}\n", .{frieza_power});
// Verify that a power of 0 causes an error to be returned
const zero_result = checkPower(0);
if (zero_result) |val| {
try stdout.print("Power: {d}\n", .{val});
} else |err| {
try stdout.print("Error occurred: {}\n", .{err});
}
}
zig run function_basic.zig === Dragon Ball Function Demo === Goku has appeared! Vegeta's power: 9500 -> doubled: 19000 Goku(9000) + Piccolo(3500) = combined power: 12500 --- Character List --- Name: Goku Power: 9000 Name: Vegeta Power: 9500 Name: Piccolo Power: 3500 Name: Trunks Power: 5000 Name: Frieza Power: 530000 --- Power Check with Error Handling --- Frieza's power check OK: 530000 Error occurred: error.ZeroPower
Overview
In Zig, functions are defined in the form fn functionName(param: Type) ReturnType { }. All parameter types and return types must be declared explicitly — type inference is not performed. Use void when a function has no return value, and use an error union type such as !void or !u32 when a function may return an error. A function marked with pub becomes a public function callable from other files or from main(). Simple functions like doublePower() and combinedPower() in the sample return a value with return expr;. Functions returning an error union type, such as checkPower(), must be handled on the calling side using try or by catching the error with catch. For more details related to functions, see also Error Union Types.
If you find any errors or copyright issues, please contact us.