liveBook · Manning

Namespace

As explained in Systems Programming with Zig

A namespace is a named scope that groups program declarations and prevents naming conflicts.

A namespace groups declarations so they can be referenced under a shared name, helping avoid naming conflicts. In Zig, any type that could contain declarations is a namespace. section 2.1.4

Use dot syntax to reach a declaration: std.debug.print names the print function inside debug, which is itself inside std. A namespace can contain functions, variables, and other namespaces. section 2.1

A struct can group functions without grouping any data. Here, animal_noises is a struct type used as a namespace; its functions are called through that type. section 2.3.1

Listing 2.15 Structs can have declarations
const std = @import("std");

// #1
const animal_noises = struct {
    // #2
    fn moo() void {
        std.debug.print("moo!\n", .{});
    }

    fn woof() void {
        std.debug.print("woof!\n", .{});
    }
};

pub fn main() void {
    // #3
    animal_noises.moo();
    animal_noises.woof();
}

A struct groups two functions and calls them using dot syntax. section 2.3.1

Source files define struct types too: the compiler parses source files and structs using the same code. Importing a Zig source file with @import returns a type containing its declarations. Mark a function or variable pub to make it accessible from other source files. section 2.3.1 section 2.1.4

Listing 2.4 main.zig
const std = @import("std");
const fibonacci = @import("fibonacci.zig").fibonacci; #1

pub fn main() void {
    const first = fibonacci(1);
    const second = fibonacci(2);
    const third = fibonacci(3);
    const fourth = fibonacci(4);
    std.debug.print("{} {} {} {}\n", .{ first, second, third, fourth });
}

The import expression accesses fibonacci directly instead of assigning a name to the source file’s namespace; the function is declared pub in its source file. section 2.1.4

Enum types are also namespaces and support method syntax, like structs. section 5.2.4

How Systems Programming with Zig covers it

How deep it goes
Explains declaration access and imports, and notes that the compiler parses source files and structs using the same code.
Examples
Groups animal-noise functions in a struct and imports a public Fibonacci function from another file.
What you can do after
Apply it in Zig to group declarations, access them with dot syntax, and import public declarations from another file.
How it connects
Connects namespaces with structs, source files, modules, enums, and declaration visibility.

Also explained in

Compare how 22 books explain namespace →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Systems Programming with Zig. The section links point to the parts of the book it draws on.