test_enums.zig (2728B) - Raw
1 const expect = @import("std").testing.expect; 2 const mem = @import("std").mem; 3 4 // Declare an enum. 5 const Type = enum { 6 ok, 7 not_ok, 8 }; 9 10 // Declare a specific enum field. 11 const c = Type.ok; 12 13 // If you want access to the ordinal value of an enum, you 14 // can specify the tag type. 15 const 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. 22 test "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. 29 const Value2 = enum(u32) { 30 hundred = 100, 31 thousand = 1000, 32 million = 1000000, 33 }; 34 test "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. 41 const Value3 = enum(u4) { 42 a, 43 b = 8, 44 c, 45 d = 4, 46 e, 47 }; 48 test "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. 59 const 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 }; 69 test "enum method" { 70 const p = Suit.spades; 71 try expect(!p.isClubs()); 72 } 73 74 // An enum can be switched upon. 75 const Foo = enum { 76 string, 77 number, 78 none, 79 }; 80 test "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. 91 const Small = enum { 92 one, 93 two, 94 three, 95 four, 96 }; 97 test "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: 102 test "@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: 108 test "@tagName" { 109 try expect(mem.eql(u8, @tagName(Small.three), "three")); 110 } 111 112 // test