Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 37 ยท Getting Started

Program Structure and Imports

Understand how a Zig program is organized: every file is a struct, top-level declarations, pub visibility, importing your own files, comments, doc comments and test blocks.

In Zig, a source file is not just text that gets compiled; it is a value. Every .zig file is an implicit struct, and its top-level declarations (const, var, fn) are the members of that struct. Once you see this, imports, namespaces and visibility rules stop being separate topics: they are all the same idea.

This lesson shows how a program is laid out, how files import each other, how comments and documentation work, and how to put tests next to the code they check.

Top-level declarations

At the top level of a file you can declare constants, variables, functions, types and tests. The order does not matter: Zig analyzes declarations lazily, so you may use a function before the line where it is defined.

ZIG
const std = @import("std");

const greeting = "Welcome";
var visits: u32 = 0;

pub fn main() void {
    visit();
    visit();
    std.debug.print("{s}! visits = {d}\n", .{ greeting, visits });
}

fn visit() void {
    visits += 1;
}

Output:

TEXT
Welcome! visits = 2

visit is defined after main and still works. Top-level const values must be known at compile time; var at the top level is global mutable state, which you should use sparingly.

Zig only compiles what is used. An unused function with a type error inside it is not reported until something refers to it. This is lazy analysis, and it is why large libraries compile quickly.

Importing your own files

Suppose you have two files side by side:

ZIG
// math_utils.zig
pub fn square(x: i32) i32 {
    return x * x;
}

pub const answer = 42;

fn secret() void {} // private: no pub
ZIG
// main.zig
const std = @import("std");
const utils = @import("math_utils.zig");

pub fn main() void {
    std.debug.print("{d} {d}\n", .{ utils.square(7), utils.answer });
}

Running zig run main.zig prints 49 42. A few rules:

  • A path ending in .zig is relative to the importing file.
  • @import("std") and @import("builtin") are special names provided by the compiler, as are names registered by the build system.
  • Only declarations marked pub can be used from another file. Calling utils.secret() is a compile error.
  • Importing the same file from several places yields the same value, so there are no duplicate copies or include guards.

You can also import just the part you need:

ZIG
const square = @import("math_utils.zig").square;
const print = @import("std").debug.print;

Files are structs

A file An implicit struct with declarations as members
@import Returns that struct as a value
pub Makes a member visible to importers

Namespaces, modules and types all use the same mechanism.

1 / 2

Namespaces inside a file

Because a struct is also a namespace, you can group declarations by nesting:

ZIG
const Geometry = struct {
    pub const pi = 3.14159;

    pub fn circleArea(r: f64) f64 {
        return pi * r * r;
    }
};

// usage: Geometry.circleArea(2.0)

There is no namespace keyword. A struct with no fields is simply a namespace.

Comments

Zig has two comment forms and no block comments:

ZIG
// A normal comment: ignored by the compiler.

/// A doc comment: documents the declaration right below it.
pub fn add(a: i32, b: i32) i32 {
    return a + b;
}

//! A top-level doc comment: documents the whole file.

Doc comments (/// and //!) are collected by zig build-exe -femit-docs (and by zig build docs in projects) into browsable HTML. Block comments are deliberately missing: every comment is a line comment, so you can always tell by looking at one line whether it is code.

Tests live next to the code

A test block is a function the test runner calls. It is ignored by a normal build:

ZIG
const std = @import("std");
const expect = std.testing.expect;

fn double(x: i32) i32 {
    return x * 2;
}

test "double doubles" {
    try expect(double(4) == 8);
    try expect(double(-3) == -6);
}
TEXT
zig test main.zig

The test passes if the block finishes without an error; expect returns an error when the condition is false. You will use tests constantly. They are also the easiest way to try small pieces of Zig, and later lessons use std.testing.expectEqual and the leak-checking std.testing.allocator.

A typical project layout

zig init creates a starter project:

TEXT
my-project/
  build.zig          the build script (written in Zig)
  build.zig.zon      package name, version, dependencies
  src/
    main.zig         executable entry point
    root.zig         library root

build.zig describes how to compile everything; src/main.zig holds main. The build system is covered in the C Interop and Build System chapter.

A stand-in you can run

Zig's pub is like C's default visibility turned around: in C, everything is visible unless you write static; in Zig, nothing is visible unless you write pub. This C stand-in keeps a counter private to one "file" using static.

C Stand-in (C): hiding a global with static

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Zig's lazy analysis has no direct C equivalent, but Rust shows a similar idea with unused code that is simply never emitted:

Rust Stand-in (Rust): modules and visibility

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is a .zig source file in the language's model?

    @import returns the file as a struct value, which is why files, types and namespaces share one mechanism.
  2. 2. What makes a function usable from another file?

    Only declarations marked pub are visible to importers.
  3. 3. Which comment form documents the declaration directly below it?

    Zig has doc comments with three slashes; it has no block comments.
  4. 4. How do you run the tests in main.zig?

    zig test compiles the file with its test blocks and runs them.

Summary

  • Each Zig file is a struct; @import("file.zig") returns it as a value.
  • Declarations are visible to other files only with pub, and their order in a file does not matter.
  • Doc comments use /// and //!; there are no block comments.
  • test "name" { ... } blocks sit beside code and run with zig test.
  • Unused code is not analyzed, so errors in it appear only when it is used.

Next: Compiler Commands and Build Modes