What does it mean when people say a file is a struct in Zig

Structs double as namespaces.

If you have a large type definition with a bunch of fields you can define it at the top level of it’s own file. For example:

//! File: Human.zig

// @This() at the top level of a file gives you the file's type, which is a struct.
// This is ueful since we aren't declaring it with a name like `const Human = struct {...`
const Human = @This();

const std = @import("std");

name: []const u8,
age: u8,

pub fn sayHello(self: Human) void {
    std.debug.print("Hi, my name is {s}.\n", .{self.name});
}

Then to use the type elsewhere:

const Human = @import("Human.zig");
const jim = Human{
    .name = "Jim",
    .age = 30,
};

There a bunch of examples of this in std, like std.fs.File, or std.Build

This also works the other way, you can define sub-namespaces without a whole new file:

pub const xyz = struct {
    pub const x = "x";
    // ...
}
10 Likes