3 ms·
You can sorta do this with Zig, but the file you're importing has to be written with that in mind. "Modules" in Zig are just structs, so you can create instance
by messe 4y ago
You can sorta do this with Zig, but the file you're importing has to be written with that in mind. "Modules" in Zig are just structs, so you can create instances of them (I'm handwaving a little bit here, but that's the gist of it).
// Greeter.zig
const std = @import("std");
const Self = @This();
name: []const u8,
pub fn greet(self: *Self) void {
std.debug.print("hello {s}!\n", .{self.name});
}
The above file is equivalent to the struct:
pub const Greeter = struct {
name: []const u8,
pub fn greeter(self: *Greeter) void {
std.debug.print("hello {s}!\n", .{self.name});
}
};
---
// main.zig
const Greeter = @import("Greeter.zig");
const greeter1 = Greeter{
.name = "Joe",
};
const greeter2 = Greeter{
.name = "Sue",
};
pub fn main() !void {
greeter1.greet();
greeter2.greet();
}
A lot of data structures in the stdlib are in written in this style.
EDIT for comparison, a non-standalone version would be written like this:
// greeter-nonstandalone.zig:
const std = @import("std");
pub var name: []const u8 = "nobody";
pub fn greet() void {
std.debug.print("hello {s}!\n", .{name});
}
// main-nonstandalone.zig
const greeter = @import("greeter-nonstandalone.zig");
pub fn main() !void {
greeter.name = "Joe";
greeter.greet();
}