usingnamespace
usingnamespace
is a top level declaration that imports all the public declarations of the operand, which must be a struct, union, or enum, into the current scope:
usingnamespace.zig
usingnamespace @import("std");
test "using std namespace" {
testing.expect(true);
}
$ zig test usingnamespace.zig
1/1 test "using std namespace"... OK
All 1 tests passed.
Instead of the above pattern, it is generally recommended to explicitly alias individual declarations. However, usingnamespace
has an important use case when organizing the public API of a file or package. For example, one might have c.zig
with all of the C imports:
pub usingnamespace @cImport({
@cInclude("epoxy/gl.h");
@cInclude("GLFW/glfw3.h");
@cDefine("STBI_ONLY_PNG", "");
@cDefine("STBI_NO_STDIO", "");
@cInclude("stb_image.h");
});
The above example demonstrates using pub
to qualify the usingnamespace
additionally makes the imported declarations pub
. This can be used to forward declarations, giving precise control over what declarations a given file exposes.