简体   繁体   中英

Global `comptime var` in Zig

In Zig, I can do this with no problems:

fn foo() void {
    comptime var num: comptime_int = 0;
    num += 1;
}

But when I try declaring the variable outside of a function, I get a compile error:

comptime var num: comptime_int = 0;

fn foo() void {
    num += 1;
}

fn bar() void {
    num += 2;
}
error: expected block or field, found 'var'

Zig version: 0.9.0-dev.453+7ef854682

Use the method used in zorrow . It defines the variable in a function (a block works too), then it returns a struct with functions for accessing it.

You can create a struct that defines get and set functions:

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);
}

In the future, you will be able to use a const with a pointer to the mutable value, and the method shown above will no longer be allowed by the compiler: https://github.com/ziglang/zig/issues/7396

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM