Z028: Inline import
Detects @import calls that are not assigned to a top-level const. Imports should be declared at the top of the file, not inline in expressions.
Examples
Bad
// expect: Z028
// expect: Z028
const builtin = @import("builtin");
const Backend = switch (builtin.os.tag) {
.linux => @import("linux.zig"),
.macos => @import("macos.zig"),
else => @compileError("unsupported"),
};// expect: Z028
fn foo() void {
const x = @import("bar.zig").baz;
_ = x;
}// expect: Z028
pub fn main() void {
const std = @import("std");
_ = std;
}Good
Assign imports to top-level constants:
const builtin = @import("builtin");
const linux = @import("linux.zig");
const macos = @import("macos.zig");
const Backend = switch (builtin.os.tag) {
.linux => linux,
.macos => macos,
else => @compileError("unsupported"),
};
Field access on imports is allowed:
const Rule = @import("rules.zig").Rule;
Calls on imports are allowed when the result lands in a top-level const
(the std.log.scoped idiom with a project-local module):
const log = @import("log.zig").scoped(.my_module);
Imports in test blocks are allowed:
test "example" {
const testing = @import("testing.zig");
testing.check();
}
Discard imports are allowed only in test blocks for pulling in tests:
test {
_ = @import("other.zig");
}Rationale
Inline imports make code harder to read and maintain:
- Discoverability: All imports at the top of a file make dependencies immediately visible
- Consistency: Standard Zig style places imports at the top
- Deduplication: Top-level imports naturally prevent duplicate imports of the same module
- Tooling: Static analysis tools work better with predictable import locations