Zig: values of type '(enum literal)' must be comptime known

Created on 4 Mar 2020  路  2Comments  路  Source: ziglang/zig

Working:

const std = @import("std");

const Mode = enum {
    Low, Medium, High, Custom
};

pub fn main() void {
    var xoroshiro = std.rand.Xoroshiro128.init(std.time.milliTimestamp());
    var random = xoroshiro.random;

    const mode: Mode = switch (random.float(f32)) {
        0.0...0.2 => .Low,
        0.2...0.4 => .Medium,
        0.4...0.6 => .High,
        0.6...1.0 => .Custom,
        else => unreachable,
    };

    std.debug.warn("{}\n", .{mode});
}

Not working:

const std = @import("std");

const Mode = enum {
    Low, Medium, High, Custom
};

pub fn main() void {
    var xoroshiro = std.rand.Xoroshiro128.init(std.time.milliTimestamp());
    var random = xoroshiro.random;

    const i: usize = 5;
    const mode: Mode = switch (i) {
        0 => .Custom,
        else => blk: {
            break :blk switch (random.float(f32)) {
                0.00...0.33 => .Low,
                0.33...0.66 => .Medium,
                0.66...1.00 => .High,
                else => unreachable
            };
        }
    };

    std.debug.warn("{}\n", .{mode});
}

Something wrong with inferring types and nested switches, maybe?

bug

Most helpful comment

Just confirming, this is a bug. It's fixed in stage 2.

All 2 comments

The type inferencer has a hard time with nested expressions:

Just confirming, this is a bug. It's fixed in stage 2.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

andrewrk picture andrewrk  路  3Comments

komuw picture komuw  路  3Comments

andrewrk picture andrewrk  路  3Comments

fengb picture fengb  路  3Comments

andrewrk picture andrewrk  路  3Comments