我正在使用 zig 0.7.0.
,尝试从数组中导入一组zig源文件。 每个源文件都有一个名为main
的函数(其返回类型为!void
),我希望能够调用每个函数。 数组module_names
在编译时已知。
这是我尝试的方法:
const std = @import("std");
const log = std.log;
const module_names = [_][]const u8{
"01.zig", "02.zig", "03.zig", "04.zig", "05.zig",
};
pub fn main() void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
for (module_names) |module_name, i| {
const module = @import(module_name); // this fails
log.info("i {}", .{i});
try module.main();
}
}
即使在编译时知道数组,
@import(module_name)
也会给我出现这个错误:./src/main.zig:13:32: error: unable to evaluate constant expression
const module = @import(module_name);
^
./src/main.zig:13:24: note: referenced here
const module = @import(module_name);
如果数组是在运行时动态生成并且只在运行时才知道,我可以理解这个错误,但是这里的 module_names
数组在编译时已知。所以我有点困惑...
另外,我还尝试将整个 main
体包装在一个 comptime
块中:
pub fn main() void {
comptime {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
for (module_names) |module_name, i| {
const module = @import(module_name); // no errors here
log.info("i {}", .{i});
try module.main();
}
}
}
在这里,@import(module_name)
没有出现错误,但是 log.info
出现了另一个错误:
/home/jack/.zig/lib/zig/std/mutex.zig:59:87: error: unable to evaluate constant expression
if (@cmpxchgWeak(usize, &self.state, 0, MUTEX_LOCK, .Acquire, .Monotonic) != null)
^
/home/jack/.zig/lib/zig/std/mutex.zig:65:35: note: called from here
return self.tryAcquire() orelse {
^
/home/jack/.zig/lib/zig/std/log.zig:145:60: note: called from here
const held = std.debug.getStderrMutex().acquire();
^
/home/jack/.zig/lib/zig/std/log.zig:222:16: note: called from here
log(.info, scope, format, args);
^
./src/main.zig:26:21: note: called from here
log.info("i {}", .{i});
在 Zig 中是否支持这种动态导入方式?