Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
← Certified Zig Programming Expert · Lesson 4 of 5

Module Three

📖 Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
4
Certified Zig Programming Expert – Module Three

Module Three: Advanced Features and the Standard Library – Becoming a Zig Power User

“Certified Zig Programming Expert” – Master the language of modern systems programming

Module Introduction

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!

Learning Objectives

After finishing this module, you will be able to:

  • Use advanced comptime features.
  • Write and use generic functions and types.
  • Use compile-time reflection with @typeInfo.
  • Understand the Zig Build System (build.zig).
  • Write unit tests using test blocks.
  • Explore the Zig Standard Library (std).
  • Work with files, strings, and collections.
  • Use @import to organize code.
  • Interface with C using @cImport and the C ABI.
  • Complete a mini project and practical assignment.

Warm-up Story: Ada’s Big Project

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.

Main Lessons

Lesson 1: Advanced comptime Metaprogramming

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:

  1. Mark parameters with comptime.
  2. Write recursion or loops.
  3. Call with comptime to evaluate.
  4. Use the result at runtime.

Mini summary: Advanced comptime lets you generate code at compile time. It makes programs faster.

Lesson 2: Generic Functions and Types

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:

  1. Use comptime T: type for the type.
  2. Use T in the function body.
  3. For generic types, return a struct from a function.
  4. Call with a specific type.

Mini summary: Generics let you write code for many types. Use comptime T: type.

Lesson 3: Compile-Time Reflection with @typeInfo

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:

  1. Use @typeInfo(T) to get info.
  2. Switch on the kind of type.
  3. Handle each kind.

Mini summary: @typeInfo gives type info at compile time. It enables powerful generic code.

Lesson 4: The Zig Build System (build.zig)

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:

  1. Create a build.zig file.
  2. Define the executable or library.
  3. Set source file, target, and optimize options.
  4. Add install and run steps.
  5. Run zig build or zig build run.

Mini summary: The build system organizes complex projects. Use build.zig and zig build.

Lesson 5: Writing Unit Tests

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:

  1. Import std.
  2. Write test "description" { ... }.
  3. Use try std.testing.expect(...).
  4. Run with zig test.

Mini summary: Tests verify your code. Write them with test blocks and run with zig test.

Lesson 6: The Zig Standard Library (std)

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.

Lesson 7: Working with Files

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:

  1. Open or create a file.
  2. Use defer file.close().
  3. Read with readAll or write with writeAll.
  4. Handle errors with try.

Mini summary: Use std.fs for files. Always close with defer.

Lesson 8: Working with Strings

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:

  1. Use []const u8 for strings.
  2. Format with std.fmt.allocPrint or std.fmt.bufPrint.
  3. Use std.mem for searching, splitting, trimming.
  4. Free allocated strings with defer.

Mini summary: Strings are []const u8. Use std.fmt and std.mem.

Lesson 9: Collections and Data Structures

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:

  1. Choose the right collection.
  2. Initialize with an allocator.
  3. Use defer to deinit.
  4. Add, remove, and access items.

Mini summary: Collections like ArrayList and HashMap organize data. Use them with allocators.

Lesson 10: Organizing Code with @import

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:

  1. Create a file with pub functions.
  2. In another file, use @import("file.zig").
  3. Use the imported functions with dot syntax.

Mini summary: @import splits code into files. Use pub to expose functions.

Lesson 11: Interfacing with C

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:

  1. Use @cImport to import C headers.
  2. Call C functions with c.functionName.
  3. Link C libraries in build.zig if needed.

Mini summary: Zig can call C code with @cImport. This lets you reuse C libraries.

Lesson 12: Common Mistakes in Advanced Zig

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:

MistakeWhat HappensHow to Fix
Forgetting to close filesResource leakUse defer file.close()
Not freeing stringsMemory leakUse defer allocator.free()
Wrong comptime usageCompile errorsUse carefully and test
Bad build.zig structureBuild failsFollow template
Missing test assertionsBugs not caughtWrite specific tests
Wrong C typesCrashesCheck C headers

Mini summary: Common mistakes include forgetting to close files and free strings. Always test and clean up.

Lesson 13: Best Practices for Advanced Zig

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:

  • Split code into modules with @import.
  • Write tests for every function.
  • Use defer right after opening resources.
  • Keep functions short and focused.
  • Use the standard library instead of rewriting.
  • Use comptime for constants and sizes.
  • Use generic functions for reusable code.
  • Use @typeInfo carefully and test.
  • Follow the C ABI when using C code.
  • Run zig fmt to keep code clean.

Mini summary: Best practices: modules, tests, defer, standard library, comptime, generics, zig fmt.

Lesson 14: Building a Multi-File Zig Project

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.

Lesson 15: Putting It All Together – Your Advanced Zig Toolkit

You now have a powerful toolkit for advanced Zig.

Your toolkit:

  • comptime metaprogramming: Generate code at compile time.
  • Generics: Write code for any type.
  • @typeInfo: Reflect on types.
  • Build system: Organize projects.
  • Unit tests: Verify code.
  • Standard library: Use ready tools.
  • Files, strings, collections: Work with data.
  • @import: Split into modules.
  • C interop: Use C libraries.

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.

Key Vocabulary

WordSimple Definition
comptimeCode that runs at compile time.
MetaprogrammingWriting code that generates code.
GenericCode that works with many types.
@typeInfoBuilt-in function for type information.
Build systemTools for organizing and building projects.
build.zigThe build configuration file.
Unit testA small program that tests a piece of code.
Standard libraryReady-made code that comes with Zig.
stdThe Zig standard library.
ArrayListA growable list.
HashMapA key-value map.
@importBring code from another file.
ModuleA separate file of code.
C interopUsing C code from Zig.
@cImportImport C headers into Zig.

Important Concepts

  • comptime generates code: Runs before your program.
  • Generics work with any type: Write once, use many times.
  • @typeInfo reflects types: Write adaptive code.
  • Build system organizes projects: Use build.zig.
  • Tests verify code: Write them in test blocks.
  • Standard library saves time: Use std.
  • Files, strings, collections: Tools for real data.
  • @import splits code: Keep files small and clear.
  • C interop reuses libraries: Use @cImport.
  • Combine everything for big projects: Build real systems.

Step-by-step Explanations

How to set up a build.zig project step by step

  1. Create a folder for your project.
  2. Create src/main.zig.
  3. Create build.zig.
  4. Add the executable definition.
  5. Run zig build.
  6. Add a run step and use zig build run.

How to write a test step by step

  1. Import std.
  2. Write test "name" { ... }.
  3. Use try std.testing.expect(...).
  4. Run zig test file.zig.

How to read a file step by step

  1. Use std.fs.cwd().openFile(path, .{}).
  2. Use defer file.close().
  3. Read with file.readAll(&buffer).
  4. Use the data.

How to use ArrayList step by step

  1. Create with std.ArrayList(T).init(allocator).
  2. Use defer list.deinit().
  3. Add items with try list.append(x).
  4. Access with list.items.

How to use C interop step by step

  1. Use @cImport with @cInclude.
  2. Call C functions with c.functionName.
  3. Link libraries in build.zig if needed.

Real-life Examples

  • Banks: Use multi-file projects for banking systems.
  • Games: Use C interop for graphics libraries.
  • Schools: Use build systems for teaching projects.
  • Homes: Use std collections for home automation.
  • Businesses: Use tests to ensure quality.

Nigerian Examples

  • Banks: Nigerian banks use build systems for reliable software.
  • Startups: Nigerian startups use C interop for speed.
  • Schools: Students write tests for their projects.
  • Businesses: Businesses use std for file handling.
  • Freelancers: Freelancers use modules for reusable code.

Fun Examples Children Can Relate To

  • Games: Use tests to check game rules.
  • Stories: Split stories into chapters.
  • Calculators: Use generics for any number.
  • Collections: Track toys with ArrayList.
  • Toys: Sort toys with HashMap.

Everyday Examples

  • Shopping: Use ArrayList for shopping lists.
  • Homework: Write tests for math problems.
  • Family: Use modules for family rules.
  • Time: Use build steps to automate tasks.
  • Money: Use HashMap for expenses.

Parent Tips

  • Encourage your child to split code into modules.
  • Show them how to write tests.
  • Teach the importance of the build system.
  • Discuss how C interop reuses old code.
  • Praise them for clean, organized code.
  • Practice with small multi-file projects.
  • Read the Zig standard library docs together.
  • Keep sessions short and fun.
  • Let them teach you what they learned.
  • Support their learning journey.

Interesting Facts

  • Zig's build system is written in Zig.
  • Zig can compile C and C++ code.
  • comptime can compute nearly anything.
  • Zig's standard library is not huge, but it is powerful.
  • Zig's ArrayList is very common.
  • Zig tests run in the same language.
  • Zig supports cross-compilation easily.
  • Zig is used in production systems.

Did You Know?

  • Did you know that zig build handles everything?
  • Did you know that tests can be run automatically?
  • Did you know that Zig can read from any file?
  • Did you know that @import works like #include in C?
  • Did you know that @cImport can read C headers?
  • Did you know that comptime can loop?
  • Did you know that Zig's standard library is called std?
  • Did you know that Nigerian developers use Zig for performance?

Remember This

  • comptime generates code at compile time.
  • Generics work with any type.
  • @typeInfo gives type info.
  • build.zig organizes projects.
  • Tests verify code.
  • std provides many tools.
  • Files, strings, collections handle data.
  • @import splits code into modules.
  • @cImport lets you use C code.
  • Combine everything for big projects.

Common Mistakes

  • Forgetting to close files.
  • Not freeing strings.
  • Wrong comptime usage.
  • Bad build.zig structure.
  • Missing test assertions.
  • Wrong C types.
  • Not using defer.
  • Ignoring compiler errors.

Best Practices

  • Split code into modules.
  • Write tests for every function.
  • Use defer right after opening resources.
  • Keep functions short.
  • Use the standard library.
  • Use comptime for constants.
  • Use generics for reusable code.
  • Use @typeInfo carefully.
  • Follow the C ABI when using C code.
  • Run zig fmt often.

Illustrations and Diagrams

Project Structure

  myproject/
  ├── build.zig
  ├── src/
  │   ├── main.zig
  │   ├── math.zig
  │   └── data.zig
  └── README.md
  

Generic Function

  fn max(comptime T: type, a: T, b: T) T {
      return if (a > b) a else b;
  }
  

Test Workflow

  Write code
      |
      V
  Write test
      |
      V
  Run zig test
      |
      V
  Fix errors
      |
      V
  Pass ✅
  

File Handling

  openFile → defer close → read/write → use data
  

Your Learning Journey

  Module 1: Zig Basics
        |
        V
  Module 2: Memory & Errors
        |
        V
  Module 3: Advanced Features
        |
        V
  Module 4: Real Projects
        |
        V
  Zig Expert 🎉
  

Comparison Tables

comptime vs runtime

Featurecomptimeruntime
WhenCompile timeRun time
SpeedFastSlower
Best forConstants, genericsDynamic data

ArrayList vs Array

FeatureArrayListArray
SizeGrowsFixed
MemoryAllocatorStack/static
Best forUnknown countKnown count

@import vs @cImport

Feature@import@cImport
Used forZig filesC headers
LanguageZigC
PurposeModulesC interop

Test vs Debug Print

FeatureTestDebug Print
PurposeVerify codeShow data
RunsOn demandAlways
Use forQualityDebugging

Lesson Summaries

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.

End-of-Module Summary

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!

Frequently Asked Questions

  1. What is comptime metaprogramming? Code that runs at compile time.
  2. What are generics? Code that works with any type.
  3. What is @typeInfo? A function that gives type information.
  4. What is build.zig? The configuration file for the Zig Build System.
  5. How do I write a test? Use test "name" { ... } and zig test.
  6. What is the standard library? Ready-made Zig code called std.
  7. How do I read a file? Use std.fs.cwd().openFile.
  8. What is ArrayList? A growable list in std.
  9. How do I split code? Use @import to bring in other files.
  10. How do I use C code? Use @cImport to import C headers.

Matching Exercises

Match the term to its meaning.

TermMeaning
1. comptimeA. Splits code into files
2. build.zigB. Compile-time code
3. TestC. Organizes project build
4. @importD. Verifies code
5. @cImportE. Imports C code

Answers: 1-B, 2-C, 3-D, 4-A, 5-E

Scenario-based Exercises

  1. Scenario: You want to write a function that works with any type. What do you do?
    Answer: Use a generic with comptime T: type.
  2. Scenario: You want to build a multi-file project. What do you use?
    Answer: build.zig and @import.
  3. Scenario: You want to test your code. What do you do?
    Answer: Write a test block and run zig test.
  4. Scenario: You want to read from a file. What do you use?
    Answer: std.fs.cwd().openFile.
  5. Scenario: You want to call C functions. What do you use?
    Answer: @cImport.

Group Activity

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.

Individual Activity

Task: Write a Zig program that:

  • Uses @import to bring in a helper file.
  • Uses std.ArrayList to store some numbers.
  • Uses a generic function to find the maximum.
  • Writes a test for the generic function.
  • Reads and writes a small file.

Hint: Start with small features and add one at a time.

Mini Project

Project: “My Multi-File Zig Tool”

Create a Zig project that:

  • Has a build.zig file.
  • Has main.zig as the entry point.
  • Has a math.zig module with a generic max function.
  • Has a data.zig module with a struct and ArrayList usage.
  • Reads a small text file and prints its contents.
  • Writes a summary file.
  • Has at least two tests.
  • Runs with zig build run.

Example output:

  Read 5 lines from input.txt
  Max value: 42
  Wrote summary to output.txt
  All tests passed ✅
  

Practical Assignment

Assignment: Build a small command-line tool in Zig. The tool should:

  1. Take a file name as input.
  2. Read the file line by line.
  3. Count the lines.
  4. Find the longest line.
  5. Print a summary.
  6. Write the summary to another file.
  7. Have at least three tests.
  8. Use build.zig to build and run.
  9. Use defer to close files.
  10. Handle errors with try and catch.

Submit: Your project folder with all .zig files and a screenshot of the output.

Key Takeaways

  • comptime generates code at compile time.
  • Generics work with any type.
  • @typeInfo gives type info.
  • build.zig organizes projects.
  • Tests verify code.
  • std provides many tools.
  • Files, strings, collections handle data.
  • @import splits code into modules.
  • @cImport lets you use C code.
  • Combine everything for big projects.

Classroom Discussion Questions

  1. What is comptime metaprogramming, and why is it useful?
  2. How do generics help you write less code?
  3. What does @typeInfo tell you about a type?
  4. Why is the Zig Build System useful?
  5. Why should you write tests?
  6. What can you find in the Zig Standard Library?
  7. How do you read and write files in Zig?
  8. How does @import help organize code?
  9. How does @cImport let you use C code?
  10. What did Ada learn from her big project?

Preparation for Module Four

In Module Four, we will build real-world projects and prepare for certification. We will cover:

  • Concurrency with threads and async patterns.
  • Networking and sockets in Zig.
  • Cross-compilation and Zig CC.
  • Performance optimization and benchmarking.
  • Packaging and publishing Zig libraries.
  • The certification project and exam preparation.

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

🏆 Get Certified

🔒

Earn this certificate

Every lesson is already free to read. Sign up, finish the lessons, pass the exam (₦2,000 or 20,000 coins), and get a verified certificate with your name on it.

🎓 Sign Up to Get Certified
🛠️ Practice Tools
Hands-on simulators & labs - subscription required.
→
🎯 Internship Tasks
Real-world tasks to build your portfolio - unlock them with a subscription.
→