Is there any way to do wildcard imports? I’m looking to make all functions from one file available in another without prefixing or having to declare each
I think you’re looking for usingnamespace
, as in usingnamespace @import("other_file.zig");
Why do you need this?
I’ve tried, with this simple example I get:
use of undeclared identifier ‘selectMin’
// util.zig
pub fn select(check: bool, v1: anytype, v2: anytype) @TypeOf(v1) {
return if (check) v1 else v2;
}
pub fn selectMin(v1: anytype, v2: anytype) @TypeOf(v1) {
return select(v1 > v2, v2, v1);
}
// main.zig
usingnamespace @import("util.zig");
pub fn myFn(v1: u8, v2: u8) u8 {
return selectMin(v1, v2);
}
Is this stack overflow? lol
So I can leverage util files without prefixing everything or having to declare an obscene amount of imports.
Wildcard imports are available in many languages
Just to clarify, usingnamespace @import("file.zig")
will forward all public declarations but won’t make them automatically available in the current scope without a prefix.
If you have a file.zig
that looks like this:
const std = @import("std");
pub fn hello() void {
std.debug.print("Hello!\n", .{});
}
The following won’t compile and will tell you that hello
is undeclared:
usingnamespace @import("file.zig");
pub fn main() void {
hello();
}
Replacing it with @This().hello()
will work, but it’s probably not what you want. If your goal is reduce typing your best option is putting them in a struct with a short name:
const z = struct {
usingnamespace @import("file.zig");
};
pub fn main() !void {
z.hello();
}
Making the declarations available unprefixed is only possible by manually redeclaring each one individually. I could be wrong but to me this seems to be a deliberate design choice stemming from wanting Zig code to be as readable as possible and for it to always be clear where each declaration comes from (nothing should ever “magically” appear in scope).
Yeah, sorry, I was curious. I understand now with the example.
yep, it’s also leveraged in the compiler implementation and autodoc aswell.
No my bad, I misread you and it’s been a long night.
Many devs have very strong opinions about this and I read your response as one of those instead of being genuinely curious.
They can be used improperly, but certainly have a time and place. One of which being reducing code bloat and helping readability when the prefix has no value to the identifier and you’re importing a lot from that file. You don’t want to add 100 imports to the start of a file but you also don’t want an unnecessary prefix all throughout the code
Isn’t this effectively equivalent to:
const z = @import("file.zig");
?
Yeah, they are equivalent and for single files it’s obviously more conventional to just use regular imports. The usingnamespace
variant only really makes sense if you for some reason want to gather declarations from multiple files under the same short namespace.