Zig 中的全局 `comptime var`

问题描述

在 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

解决方法

使用zorrow中使用的方法。它在函数中定义变量(块也可以),然后返回一个带有访问它的函数的结构体。

您可以创建一个定义 getset 函数的结构:

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