usingnamespace

usingnamespace is a declaration that imports all the public declarations of the operand, which must be a struct, union, or enum, into the current scope:

usingnamespace.zig

  1. usingnamespace @import("std");
  2. test "using std namespace" {
  3. try testing.expect(true);
  4. }
  1. $ zig test usingnamespace.zig
  2. Test [1/1] test "using std namespace"...
  3. All 1 tests passed.

usingnamespace can also be used in containers:

usingnamespace_inside_struct.zig

  1. test "using namespace inside struct" {
  2. const L = struct {
  3. usingnamespace struct {
  4. pub fn f() void {}
  5. };
  6. };
  7. L.f();
  8. }
  1. $ zig test usingnamespace_inside_struct.zig
  2. Test [1/1] test "using namespace inside struct"...
  3. 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:

  1. pub usingnamespace @cImport({
  2. @cInclude("epoxy/gl.h");
  3. @cInclude("GLFW/glfw3.h");
  4. @cDefine("STBI_ONLY_PNG", "");
  5. @cDefine("STBI_NO_STDIO", "");
  6. @cInclude("stb_image.h");
  7. });

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.