在Zig中,我可以毫无问题地做到这一点:
fn foo() void {
comptime var num: comptime_int = 0;
num += 1;
}但是当我试图在函数外部声明变量时,我得到了一个编译错误:
comptime var num: comptime_int = 0;
fn foo() void {
num += 1;
}
fn bar() void {
num += 2;
}error: expected block or field, found 'var'Zig版本: 0.9.0-dev.453+7ef854682
发布于 2021-07-28 13:48:21
使用zorrow中使用的方法。它在一个函数中定义变量(一个块也可以),然后返回一个带有访问它的函数的结构。
您可以创建定义get和set函数的结构:
const num = block_name: {
comptime var self: comptime_int = 0;
const result = struct {
fn get() comptime_int {
return self;
}
fn increment(amount: comptime_int) void {
self += amount;
}
};
break :block_name result;
};
fn foo() void {
num.increment(1);
}
fn bar() void {
num.increment(2);
}将来,您将能够使用带有指向变量值的指针的const,编译器将不再允许使用上面显示的方法:https://github.com/ziglang/zig/issues/7396
https://stackoverflow.com/questions/68555025
复制相似问题