Zig NEWS

Govind
Govind

Posted on

Zig files are structs

While exploring the Allocator interface, I came the lines

// The type erased pointer to the allocator implementation
ptr: *anyopaque,
vtable: *const VTable,
Enter fullscreen mode Exit fullscreen mode

in the file that felt out of place. The seemed like file level globals, but without a var or a const declaration.
Turns out, files are compiled into structs.

As an example, this is how we can verify this.

cat module1.zig
a: u32,
b: u32,
Enter fullscreen mode Exit fullscreen mode
cat module2.zig
const m1 = @import("module1.zig");
const std = @import("std");

pub fn main() !void {
    var s = m1{ .a = 43, .b = 46 };
    std.debug.print("{}\n", .{s.a});
}
Enter fullscreen mode Exit fullscreen mode

Running module2.zig using zig run module2.zig, I get :
43

Top comments (2)

Collapse
 
webermartin profile image
weber-martin

This is also documented here: ziglang.org/documentation/0.9.1/#i...

Zig source files are implicitly structs, with a name equal to the file's basename with the extension truncated. @import returns the struct type corresponding to the file.

Collapse
 
gowind profile image
Govind

Thanks, I did not notice this in the std. documentation ! Leaving this here anyway for someone if they are interested.