Zig structs vs Java classes

Take care not to confuse what you’re calling “members” here and struct fields though, which can just as well be declared at the top level and are always public:

//! A top-level module.

var inner: u32 = 0;
pub const foo: i32 = 123; // Yes, this needs `pub`...

// But this is a field, and all fields are public.
// Mind the comma.
number: u32,

pub fn init() @This() {
    const x: @This() = .{ .number = inner };
    inner += 1;
    return x;
}
// main.zig

const std = @import("std");
const Mod = @import("Module.zig");

pub fn main() void {
    const m = Mod.init();
    std.debug.print("m.number = {}\n", .{m.number});

    std.debug.print("next is {}\n", .{Mod.init().number});
    std.debug.print("next is {}\n", .{Mod.init().number});
    std.debug.print("next is {}\n", .{Mod.init().number});
    std.debug.print("next is {}\n", .{Mod.init().number});
}
$ zig run main.zig
m.number = 0
next is 1
next is 2
next is 3
next is 4
1 Like