我正在尝试构建一个“静态”数据数组,并继续与编译时/运行时故障作斗争。这是我正在尝试的浓缩版本:
const std = @import("std");
var global_array: [4]u8 = undefined;
fn fill(comptime arr: []u8) void {
for (arr) |*c| {
c.* = 'Z';
}
}
test "Comptime mutation" {
comptime {
fill(&global_array);
}
try std.testing.expect(global_array[0] == 'Z');
}
这会产生错误消息:
error: unable to evaluate comptime expression
c.* = 'Z';
~~~~^~~~~
note: operation is runtime due to this operand
c.* = 'Z';
~^~
note: called from here
fill(&t);
我发现这个答案似乎在 load_error_codes_with_context 函数中使用相同的模式,但无法发现差异 -> https://stackoverflow.com/a/77357351/9756362
我的问题是:
正如sigod所指出的,将 comptime var 访问包装在一个专用结构中,如this SO answer解决了问题:
const global_array = blk: {
comptime var array: [4]u8 = undefined;
const result = struct {
fn get() []u8 {
return &array;
}
};
break :blk result;
};
fn fill(comptime arr: []u8) void {
for (arr) |*c| {
c.* = 'Z';
}
}
test "Comptime mutation" {
comptime {
fill(global_array.get());
}
try expect(global_array.get()[0] == 'Z');
}