“Certified Zig Programming Expert” – Master the language of modern systems programming
Welcome back, young Zig programmer! In Module One, you learned the basics of Zig: variables, functions, structs, enums, arrays, slices, and strings. In Module Two, you learned about memory management and error handling: pointers, allocators, defer, optionals, error unions, try, catch, comptime, and generics.
Now it is time to go deeper. In Module Three, we will learn about advanced features and the standard library. This is where Zig becomes truly powerful. We will explore advanced comptime metaprogramming, the Zig Build System, unit testing, the standard library, and how to work with C code.
Think of this module as moving from a small workshop to a large factory. You will learn to build bigger, more complex programs. You will learn to organize your code, test it, and use the many tools Zig provides. By the end of this module, you will be a Zig power user.
Let's begin!
After finishing this module, you will be able to:
comptime features.@typeInfo.build.zig).std).@import to organize code.@cImport and the C ABI.Ada is 15 years old and lives in Abuja. She has been learning Zig for a few weeks and has built several small programs. Now she wants to build something bigger: a small tool that helps her father’s shop keep track of inventory.
Ada started writing code, but it quickly became messy. She had one big file with hundreds of lines. She had no tests, and she kept making the same mistakes. She also needed to use code from a C library her father already had.
Her mentor said, “Ada, it is time to learn advanced Zig. You will learn how to organize your code into modules, use the build system, write tests, and even use C libraries. This is how real programmers build big projects.”
Ada learned about the Zig Build System and created a build.zig file. She split her code into several files using @import. She wrote tests using test blocks. She used the standard library for file handling. And she learned how to call C functions using @cImport.
By the end of the week, Ada’s inventory tool was clean, tested, and ready to use. Her father was very proud. Ada had become a Zig power user.
Moral of the story: Advanced Zig features let you build bigger, cleaner, and more powerful programs. Learn the build system, testing, the standard library, and C interop to become a true expert.
Definition: comptime metaprogramming is writing code that runs at compile time and can generate or modify other code.
Why it is important: It makes programs faster and lets you write flexible code.
Simple explanation: Imagine writing a recipe that writes other recipes. That is what comptime can do.
Real-life example: Banks use comptime to generate efficient code.
School example: Schools use comptime for generating timetables.
Home example: Families use comptime for meal planning.
Nigerian example: Businesses use comptime for pricing rules.
Illustration:
comptime Metaprogramming:
fn power(comptime n: u8, x: i32) i32 {
if (n == 0) return 1;
return x * power(n - 1, x);
}
const result = comptime power(3, 2); // 8 at compile time
Step-by-step:
comptime.comptime to evaluate.Mini summary: Advanced comptime lets you generate code at compile time. It makes programs faster.
Definition: Generics let you write code that works with many types.
Why it is important: Generics let you write code once and reuse it.
Simple explanation: Like a shirt that fits any size.
Real-life example: Banks use generic functions for different account types.
School example: Schools use generic containers for different subjects.
Home example: Families use generic lists for different items.
Nigerian example: Traders use generic lists for different products.
Illustration:
Generic Function:
fn max(comptime T: type, a: T, b: T) T {
return if (a > b) a else b;
}
const m1 = max(i32, 3, 7); // 7
const m2 = max(f64, 3.5, 2.1); // 3.5
Generic Struct:
fn Pair(comptime T: type) type {
return struct {
first: T,
second: T,
};
}
const IntPair = Pair(i32);
Step-by-step:
comptime T: type for the type.T in the function body.struct from a function.Mini summary: Generics let you write code for many types. Use comptime T: type.
Definition: @typeInfo gives you information about a type at compile time.
Why it is important: It lets you write code that adapts to any type.
Simple explanation: Like a magnifying glass that shows you what a type is made of.
Real-life example: Banks use reflection to print reports for any data type.
School example: Schools use reflection for generic printing.
Home example: Families use reflection for flexible logs.
Nigerian example: Businesses use reflection for generic reports.
Illustration:
@typeInfo Example:
fn describe(comptime T: type) void {
const info = @typeInfo(T);
switch (info) {
.Int => std.debug.print("It's an integer!\n", .{}),
.Float => std.debug.print("It's a float!\n", .{}),
.Struct => std.debug.print("It's a struct!\n", .{}),
else => std.debug.print("Something else.\n", .{}),
}
}
describe(i32); // It's an integer!
describe(f64); // It's a float!
Step-by-step:
@typeInfo(T) to get info.Mini summary: @typeInfo gives type info at compile time. It enables powerful generic code.
Definition: The Zig Build System is a way to organize and build complex Zig projects.
Why it is important: It handles dependencies, targets, and compilation steps.
Simple explanation: Like a recipe for building your entire project.
Real-life example: Banks use build systems for their software.
School example: Schools use build systems for class projects.
Home example: Families use build systems for home automation.
Nigerian example: Businesses use build systems for their tools.
Illustration:
build.zig Example:
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const exe = b.addExecutable(.{
.name = "myprogram",
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
});
b.installArtifact(exe);
const run_cmd = b.addRunArtifact(exe);
const run_step = b.step("run", "Run the program");
run_step.dependOn(&run_cmd.step);
}
Step-by-step:
build.zig file.zig build or zig build run.Mini summary: The build system organizes complex projects. Use build.zig and zig build.
Definition: Unit tests are small programs that check if your code works.
Why it is important: Tests catch bugs early.
Simple explanation: Like checking your homework before submitting it.
Real-life example: Banks test their software before use.
School example: Students check their answers.
Home example: Families test appliances.
Nigerian example: Businesses test products.
Illustration:
Test Example:
const std = @import("std");
fn add(a: i32, b: i32) i32 {
return a + b;
}
test "add works" {
try std.testing.expect(add(2, 3) == 5);
try std.testing.expect(add(-1, 1) == 0);
}
Run with: zig test src/main.zig
Step-by-step:
std.test "description" { ... }.try std.testing.expect(...).zig test.Mini summary: Tests verify your code. Write them with test blocks and run with zig test.
Definition: The standard library is a collection of ready-made code that comes with Zig.
Why it is important: It saves time and gives you tested tools.
Simple explanation: Like a toolbox full of useful tools.
Real-life example: Banks use std for logging.
School example: Schools use std for file handling.
Home example: Families use std for timing tasks.
Nigerian example: Businesses use std for networking.
Illustration:
Common std Modules: std.debug → printing and debugging std.heap → memory allocators std.fs → file system std.mem → memory operations std.fmt → formatting std.math → math functions std.testing → testing tools std.Thread → threading std.net → networking
Mini summary: The standard library std provides many useful tools. Learn it to save time.
Definition: File handling means reading from and writing to files on your computer.
Why it is important: Files let you save data permanently.
Simple explanation: Like saving your work in a notebook.
Real-life example: Banks save transaction records in files.
School example: Schools save student data in files.
Home example: Families save shopping lists in files.
Nigerian example: Businesses save sales in files.
Illustration:
Reading a File:
const std = @import("std");
pub fn main() !void {
const file = try std.fs.cwd().openFile("data.txt", .{});
defer file.close();
var buffer: [1024]u8 = undefined;
const bytes = try file.readAll(&buffer);
std.debug.print("Read: {s}\n", .{buffer[0..bytes]});
}
Writing a File:
const file = try std.fs.cwd().createFile("out.txt", .{});
defer file.close();
try file.writeAll("Hello, file!\n");
Step-by-step:
defer file.close().readAll or write with writeAll.try.Mini summary: Use std.fs for files. Always close with defer.
Definition: Strings are lists of characters. Zig stores them as []const u8.
Why it is important: Strings handle text in your programs.
Simple explanation: Like writing words with letters.
Real-life example: Banks store names and addresses as strings.
School example: Schools store student names as strings.
Home example: Families store messages as strings.
Nigerian example: Businesses store product names as strings.
Illustration:
String Operations:
const std = @import("std");
const name = "Ada";
const greeting = try std.fmt.allocPrint(
allocator, "Hello, {s}!", .{name}
);
defer allocator.free(greeting);
std.debug.print("{s}\n", .{greeting});
Common std.mem functions:
- eql(a, b) → equal?
- startsWith(a, b) → starts with?
- indexOf(a, b) → find position
- split(a, b) → split by delimiter
- trim(a, b) → remove whitespace
Step-by-step:
[]const u8 for strings.std.fmt.allocPrint or std.fmt.bufPrint.std.mem for searching, splitting, trimming.defer.Mini summary: Strings are []const u8. Use std.fmt and std.mem.
Definition: Collections are containers for many values.
Why it is important: Collections help organize data.
Simple explanation: Like boxes for different kinds of items.
Real-life example: Banks use lists for transactions.
School example: Schools use maps for student grades.
Home example: Families use lists for shopping.
Nigerian example: Businesses use maps for product prices.
Illustration:
Common std Collections:
std.ArrayList(T) → growable list
std.StringHashMap(V) → key-value map
std.AutoHashMap(K, V) → generic map
std.Buffer → dynamic string (older)
Example with ArrayList:
var list = std.ArrayList(i32).init(allocator);
defer list.deinit();
try list.append(1);
try list.append(2);
for (list.items) |item| {
std.debug.print("{d}\n", .{item});
}
Step-by-step:
defer to deinit.Mini summary: Collections like ArrayList and HashMap organize data. Use them with allocators.
Definition: @import brings code from another file into your program.
Why it is important: It helps split large programs into small files.
Simple explanation: Like bringing a tool from another toolbox.
Real-life example: Banks split code into modules.
School example: Schools split subjects into books.
Home example: Families keep tools in different drawers.
Nigerian example: Businesses organize departments.
Illustration:
Module Example:
File: math.zig
pub fn add(a: i32, b: i32) i32 {
return a + b;
}
File: main.zig
const math = @import("math.zig");
pub fn main() void {
std.debug.print("{d}\n", .{math.add(2, 3)});
}
Step-by-step:
pub functions.@import("file.zig").Mini summary: @import splits code into files. Use pub to expose functions.
Definition: Interfacing with C means calling C functions from Zig.
Why it is important: Zig can use existing C libraries.
Simple explanation: Like speaking another language to use a friend's tools.
Real-life example: Banks use C libraries for performance.
School example: Schools use C libraries for math.
Home example: Families use C libraries for games.
Nigerian example: Businesses use C libraries for speed.
Illustration:
C Interop Example:
const c = @cImport({
@cInclude("stdio.h");
});
pub fn main() void {
_ = c.printf("Hello from C!\n");
}
Step-by-step:
@cImport to import C headers.c.functionName.build.zig if needed.Mini summary: Zig can call C code with @cImport. This lets you reuse C libraries.
Definition: Mistakes happen. Knowing them helps you avoid them.
Why it is important: Advanced code can hide subtle bugs.
Simple explanation: Like a small mistake in a big recipe.
Real-life example: Banks check their code carefully.
School example: Students check their projects.
Home example: Families double-check plans.
Nigerian example: Businesses test their tools.
Table of common mistakes:
| Mistake | What Happens | How to Fix |
|---|---|---|
| Forgetting to close files | Resource leak | Use defer file.close() |
| Not freeing strings | Memory leak | Use defer allocator.free() |
Wrong comptime usage | Compile errors | Use carefully and test |
| Bad build.zig structure | Build fails | Follow template |
| Missing test assertions | Bugs not caught | Write specific tests |
| Wrong C types | Crashes | Check C headers |
Mini summary: Common mistakes include forgetting to close files and free strings. Always test and clean up.
Definition: Best practices are good habits for clean, safe code.
Why it is important: Good habits prevent bugs and make code easy to read.
Simple explanation: Like keeping your tools sharp and organized.
Real-life example: Banks follow strict standards.
School example: Schools have writing guidelines.
Home example: Families keep the house tidy.
Nigerian example: Businesses use consistent procedures.
List of best practices:
@import.defer right after opening resources.comptime for constants and sizes.@typeInfo carefully and test.zig fmt to keep code clean.Mini summary: Best practices: modules, tests, defer, standard library, comptime, generics, zig fmt.
Let’s build a complete multi-file project.
Step 1: Create a project folder.
Step 2: Create src/ for source files.
Step 3: Create src/main.zig with the entry point.
Step 4: Create src/math.zig with helper functions.
Step 5: Create src/data.zig with structs.
Step 6: Create build.zig.
Step 7: Write tests in each file.
Step 8: Run zig build run.
Illustration:
Project Structure: myproject/ ├── build.zig ├── src/ │ ├── main.zig │ ├── math.zig │ └── data.zig └── README.md main.zig imports math.zig and data.zig. build.zig compiles everything together.
Mini summary: Multi-file projects organize code. Use @import and build.zig.
You now have a powerful toolkit for advanced Zig.
Your toolkit:
Illustration:
Your Toolkit: +----------+ +----------+ +----------+ | comptime | | Generics | |@typeInfo | +----------+ +----------+ +----------+ +----------+ +----------+ +----------+ | build.zig| | Tests | | std | +----------+ +----------+ +----------+ +----------+ +----------+ +----------+ | Files | | @import | | C interop| +----------+ +----------+ +----------+
Mini summary: Your advanced toolkit lets you build bigger, cleaner programs. Use it with confidence.
| Word | Simple Definition |
|---|---|
| comptime | Code that runs at compile time. |
| Metaprogramming | Writing code that generates code. |
| Generic | Code that works with many types. |
| @typeInfo | Built-in function for type information. |
| Build system | Tools for organizing and building projects. |
| build.zig | The build configuration file. |
| Unit test | A small program that tests a piece of code. |
| Standard library | Ready-made code that comes with Zig. |
| std | The Zig standard library. |
| ArrayList | A growable list. |
| HashMap | A key-value map. |
| @import | Bring code from another file. |
| Module | A separate file of code. |
| C interop | Using C code from Zig. |
| @cImport | Import C headers into Zig. |
build.zig.test blocks.std.@cImport.src/main.zig.build.zig.zig build.zig build run.std.test "name" { ... }.try std.testing.expect(...).zig test file.zig.std.fs.cwd().openFile(path, .{}).defer file.close().file.readAll(&buffer).std.ArrayList(T).init(allocator).defer list.deinit().try list.append(x).list.items.@cImport with @cInclude.c.functionName.build.zig if needed.comptime can compute nearly anything.ArrayList is very common.zig build handles everything?@import works like #include in C?@cImport can read C headers?comptime can loop?std?comptime generates code at compile time.@typeInfo gives type info.build.zig organizes projects.std provides many tools.@import splits code into modules.@cImport lets you use C code.comptime usage.build.zig structure.defer.defer right after opening resources.comptime for constants.@typeInfo carefully.zig fmt often.myproject/ ├── build.zig ├── src/ │ ├── main.zig │ ├── math.zig │ └── data.zig └── README.md
fn max(comptime T: type, a: T, b: T) T {
return if (a > b) a else b;
}
Write code
|
V
Write test
|
V
Run zig test
|
V
Fix errors
|
V
Pass ✅
openFile → defer close → read/write → use data
Module 1: Zig Basics
|
V
Module 2: Memory & Errors
|
V
Module 3: Advanced Features
|
V
Module 4: Real Projects
|
V
Zig Expert 🎉
| Feature | comptime | runtime |
|---|---|---|
| When | Compile time | Run time |
| Speed | Fast | Slower |
| Best for | Constants, generics | Dynamic data |
| Feature | ArrayList | Array |
|---|---|---|
| Size | Grows | Fixed |
| Memory | Allocator | Stack/static |
| Best for | Unknown count | Known count |
| Feature | @import | @cImport |
|---|---|---|
| Used for | Zig files | C headers |
| Language | Zig | C |
| Purpose | Modules | C interop |
| Feature | Test | Debug Print |
|---|---|---|
| Purpose | Verify code | Show data |
| Runs | On demand | Always |
| Use for | Quality | Debugging |
Lesson 1: Advanced comptime generates code at compile time.
Lesson 2: Generics work with any type.
Lesson 3: @typeInfo gives type information.
Lesson 4: build.zig organizes projects.
Lesson 5: Tests verify code with test blocks.
Lesson 6: std provides many useful tools.
Lesson 7: Files are read and written with std.fs.
Lesson 8: Strings use std.fmt and std.mem.
Lesson 9: Collections like ArrayList and HashMap store data.
Lesson 10: @import splits code into modules.
Lesson 11: C interop uses @cImport.
Lesson 12: Common mistakes: forgetting to close files, not freeing strings.
Lesson 13: Best practices: modules, tests, defer, std.
Lesson 14: Multi-file projects organize code well.
Lesson 15: Your advanced toolkit lets you build bigger programs.
Congratulations! You have finished Module Three of the Certified Zig Programming Expert course. You learned advanced comptime metaprogramming, generics, and compile-time reflection with @typeInfo. You learned about the Zig Build System and how to use build.zig. You learned to write unit tests, use the standard library, handle files, strings, and collections. You learned how to split code with @import and how to interface with C using @cImport. You learned common mistakes and best practices. Most importantly, you can now build bigger, cleaner, and more powerful Zig programs. In the next module, you will build real-world projects and earn your certification. Keep practising, and you will become a Zig expert!
test "name" { ... } and zig test.std.std.fs.cwd().openFile.std.@import to bring in other files.@cImport to import C headers.Match the term to its meaning.
| Term | Meaning |
|---|---|
| 1. comptime | A. Splits code into files |
| 2. build.zig | B. Compile-time code |
| 3. Test | C. Organizes project build |
| 4. @import | D. Verifies code |
| 5. @cImport | E. Imports C code |
Answers: 1-B, 2-C, 3-D, 4-A, 5-E
comptime T: type.build.zig and @import.test block and run zig test.std.fs.cwd().openFile.@cImport.Title: “Build a Multi-File Zig Project Together”
Instructions: In groups of 3–4, create a small multi-file Zig project with at least three files: main.zig, math.zig, and data.zig. Write tests in each file. Create a build.zig file. One person writes main.zig, one person writes math.zig, one person writes data.zig, and one person writes build.zig. Run the project with zig build run. Share your project with the class.
Goal: Practice building a multi-file Zig project with tests and a build system.
Task: Write a Zig program that:
@import to bring in a helper file.std.ArrayList to store some numbers.Hint: Start with small features and add one at a time.
Project: “My Multi-File Zig Tool”
Create a Zig project that:
build.zig file.main.zig as the entry point.math.zig module with a generic max function.data.zig module with a struct and ArrayList usage.zig build run.Example output:
Read 5 lines from input.txt Max value: 42 Wrote summary to output.txt All tests passed ✅
Assignment: Build a small command-line tool in Zig. The tool should:
build.zig to build and run.defer to close files.try and catch.Submit: Your project folder with all .zig files and a screenshot of the output.
comptime generates code at compile time.@typeInfo gives type info.build.zig organizes projects.std provides many tools.@import splits code into modules.@cImport lets you use C code.In Module Four, we will build real-world projects and prepare for certification. We will cover:
To prepare, make sure you have completed the practical assignment and have your multi-file project ready. Review the key vocabulary. Think about what kind of project you would like to build. Bring your curiosity!
See you in Module Four!
End of Module Three – Certified Zig Programming Expert