Unable to add build option with a slice of enums

Hello, I wanted to add a build option of type []T where T is an enum I made. However, it seems like the Zig build system generated incorrect code for the options.zig file, resulting in a compile error.

I’m using Zig version 0.12.0-dev.3522+b88ae8dbd.

Here is the build.zig code for example:

const std = @import("std");

const Animal = enum {
    refrigerator,
    sun,
    apple,
};

pub fn build(b: *std.Build) void {
    const target = b.standardTargetOptions(.{});
    const optimize = b.standardOptimizeOption(.{});

    const opts = b.addOptions();
    opts.addOption([]Animal, "animals", @constCast(&[_]Animal{ .sun, .apple, .refrigerator }));

    const exe = b.addExecutable(.{
        .name = "test",
        .root_source_file = .{ .path = "main.zig" },
        .target = target,
        .optimize = optimize,
    });
    b.installArtifact(exe);

    exe.root_module.addImport("options", opts.createModule());
}

Here is the main.zig file:

const _ = @import("options");

pub fn main() void {}

Here is the generated options.zig file:

pub const animals: []build.Animal = &[_]build.Animal {
        pub const @"build.Animal" = enum (u2) {
        refrigerator = 0,
        sun = 1,
        apple = 2,
    };
        };

Welcome to the forum.

In addOption implementation, it seems to pass enum type decl as a option value.

If you want to pass flag enum, using std.enums.EnumSet type may be useful.

https://ziglang.org/documentation/master/std/#std.EnumSet

For instance:

opts.addOption(std.enums.EnumSet(Animal), "animals", std.enums.EnumSet(Animal).init(.{ .sun = true, .apple = true,  }));

Or std.enums.EnumFieldStruct type mey be also useful.

https://ziglang.org/documentation/master/std/#std.enums.EnumFieldStruct

 opts.addOption(std.enums.EnumFieldStruct(Animal, bool, false), "animals", .{ .sun = true, .apple = true,  });
4 Likes

It seems like std.enums.EnumFieldStruct is what I’m looking for. Thanks for the helpful answer!