enum

    Shell

    1. 1/7 test "enum ordinal value"... OK
    2. 2/7 test "set enum ordinal value"... OK
    3. 3/7 test "enum method"... OK
    4. 4/7 test "enum variant switch"... OK
    5. 5/7 test "std.meta.Tag"... OK
    6. 6/7 test "@typeInfo"... OK
    7. 7/7 test "@tagName"... OK
    8. All 7 tests passed.

    See also:

    By default, enums are not guaranteed to be compatible with the C ABI:

    test.zig

    1. export fn entry(foo: Foo) void { _ = foo; }

    For a C-ABI-compatible enum, provide an explicit tag type to the enum:

    test.zig

    1. const Foo = enum(c_int) { a, b, c };
    2. export fn entry(foo: Foo) void { _ = foo; }

    Shell

    1. $ zig build-obj test.zig

    Enum literals allow specifying the name of an enum field without specifying the enum type:

    Shell

    1. 1/2 test "enum literals"... OK
    2. 2/2 test "switch using enum literals"... OK
    3. All 2 tests passed.

    A Non-exhaustive enum can be created by adding a trailing ‘_‘ field. It must specify a tag type and cannot consume every enumeration value.

    @intToEnum on a non-exhaustive enum involves the safety semantics of to the integer tag type, but beyond that always results in a well-defined enum value.

    A switch on a non-exhaustive enum can include a ‘_‘ prong as an alternative to an else prong with the difference being that it makes it a compile error if all the known tag names are not handled by the switch.

    1. const std = @import("std");
    2. const expect = std.testing.expect;
    3. const Number = enum(u8) {
    4. one,
    5. two,
    6. three,
    7. };
    8. test "switch on non-exhaustive enum" {
    9. const number = Number.one;
    10. const result = switch (number) {
    11. .one => true,
    12. .two,
    13. .three => false,
    14. _ => false,
    15. };
    16. try expect(result);
    17. const is_one = switch (number) {
    18. .one => true,
    19. else => false,
    20. };
    21. }

    Shell