master
1const expect = @import("std").testing.expect;
2const mem = @import("std").mem;
3
4// Declare an enum.
5const Type = enum {
6 ok,
7 not_ok,
8};
9
10// Declare a specific enum field.
11const c = Type.ok;
12
13// If you want access to the ordinal value of an enum, you
14// can specify the tag type.
15const Value = enum(u2) {
16 zero,
17 one,
18 two,
19};
20// Now you can cast between u2 and Value.
21// The ordinal value starts from 0, counting up by 1 from the previous member.
22test "enum ordinal value" {
23 try expect(@intFromEnum(Value.zero) == 0);
24 try expect(@intFromEnum(Value.one) == 1);
25 try expect(@intFromEnum(Value.two) == 2);
26}
27
28// You can override the ordinal value for an enum.
29const Value2 = enum(u32) {
30 hundred = 100,
31 thousand = 1000,
32 million = 1000000,
33};
34test "set enum ordinal value" {
35 try expect(@intFromEnum(Value2.hundred) == 100);
36 try expect(@intFromEnum(Value2.thousand) == 1000);
37 try expect(@intFromEnum(Value2.million) == 1000000);
38}
39
40// You can also override only some values.
41const Value3 = enum(u4) {
42 a,
43 b = 8,
44 c,
45 d = 4,
46 e,
47};
48test "enum implicit ordinal values and overridden values" {
49 try expect(@intFromEnum(Value3.a) == 0);
50 try expect(@intFromEnum(Value3.b) == 8);
51 try expect(@intFromEnum(Value3.c) == 9);
52 try expect(@intFromEnum(Value3.d) == 4);
53 try expect(@intFromEnum(Value3.e) == 5);
54}
55
56// Enums can have methods, the same as structs and unions.
57// Enum methods are not special, they are only namespaced
58// functions that you can call with dot syntax.
59const Suit = enum {
60 clubs,
61 spades,
62 diamonds,
63 hearts,
64
65 pub fn isClubs(self: Suit) bool {
66 return self == Suit.clubs;
67 }
68};
69test "enum method" {
70 const p = Suit.spades;
71 try expect(!p.isClubs());
72}
73
74// An enum can be switched upon.
75const Foo = enum {
76 string,
77 number,
78 none,
79};
80test "enum switch" {
81 const p = Foo.number;
82 const what_is_it = switch (p) {
83 Foo.string => "this is a string",
84 Foo.number => "this is a number",
85 Foo.none => "this is a none",
86 };
87 try expect(mem.eql(u8, what_is_it, "this is a number"));
88}
89
90// @typeInfo can be used to access the integer tag type of an enum.
91const Small = enum {
92 one,
93 two,
94 three,
95 four,
96};
97test "std.meta.Tag" {
98 try expect(@typeInfo(Small).@"enum".tag_type == u2);
99}
100
101// @typeInfo tells us the field count and the fields names:
102test "@typeInfo" {
103 try expect(@typeInfo(Small).@"enum".fields.len == 4);
104 try expect(mem.eql(u8, @typeInfo(Small).@"enum".fields[1].name, "two"));
105}
106
107// @tagName gives a [:0]const u8 representation of an enum value:
108test "@tagName" {
109 try expect(mem.eql(u8, @tagName(Small.three), "three"));
110}
111
112// test