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

Please correct me if I am wrong, but I believe I have seen people say that a file is a struct in Zig.

I am not sure exactly what that means?

Can I create values off a file as I can off a struct that is defined like

const SuperDuperStruct = struct {}

Or when they say a file is a struct they mean something else?

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

Additionally, this is also often referred to as “container level” - just thought I’d throw that in because you’ll come across that phrase occasionally.

3 Likes