Gotchas when using a file as a struct?

Files are structs. For example:

Though it seems that these structs cannot be packed or extern.

Are there any other differences / limitations of defining structs in this way?

File struct is basically a public definition of a simple struct (with fields) outside of any namespace.

Some practices around file structs:

  • File struct should not be used as the root file.
  • File struct should have a PascalCase (TitleCase) name.
  • File struct should be referred to by the same name as the name of the file, like:
// Allocator.zig
const Allocator = @This();
2 Likes

To clarify, files are struct types, not struct instances.

So the file itself can have fields, and be instantiated, for example. But what @import returns is a type.

Correct, the type-of-type of a file can’t be declared, so there’s no way to do this.

Fun fact, this works (although there’s not much you can do with the instance):

test "instance of std" {
    const std_instance = @import("std"){};
    // prints "std"
    std.debug.print("{}\n", .{@TypeOf(std_instance)});
    switch (@typeInfo(@import("std"))) {
        .Struct => std.debug.print("std is a struct type\n", .{}),
        else => std.debug.print("std is something else\n", .{}),
    }
}
3 Likes