Zig 中的全局`comptime var`

问题描述 投票:0回答:2

在 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

mutability zig
2个回答
3
投票

使用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/问题/7396


0
投票

自 Zig 最近更新以来,已接受的答案将不再编译。这是因为它根本向运行时公开了一个 comptime var。该值需要先保存为常量,然后才能在运行时访问。 然而,由于这是一个全球状态跟踪器,似乎你真的不应该在 Zig 中这样做。由于您被要求“请在本地跟踪您所在的州”

© www.soinside.com 2019 - 2024. All rights reserved.