1const std = @import("std");
2const expectEqual = std.testing.expectEqual;
3
4const E = enum {
5 one,
6 two,
7 three,
8};
9
10const U = union(E) {
11 one: i32,
12 two: f32,
13 three,
14};
15
16const U2 = union(enum) {
17 a: void,
18 b: f32,
19
20 fn tag(self: U2) usize {
21 switch (self) {
22 .a => return 1,
23 .b => return 2,
24 }
25 }
26};
27
28test "coercion between unions and enums" {
29 const u = U{ .two = 12.34 };
30 const e: E = u; // coerce union to enum
31 try expectEqual(E.two, e);
32
33 const three = E.three;
34 const u_2: U = three; // coerce enum to union
35 try expectEqual(E.three, u_2);
36
37 const u_3: U = .three; // coerce enum literal to union
38 try expectEqual(E.three, u_3);
39
40 const u_4: U2 = .a; // coerce enum literal to union with inferred enum tag type.
41 try expectEqual(1, u_4.tag());
42
43 // The following example is invalid.
44 // error: coercion from enum '@EnumLiteral()' to union 'test_coerce_unions_enum.U2' must initialize 'f32' field 'b'
45 //var u_5: U2 = .b;
46 //try expectEqual(2, u_5.tag());
47}
48
49// test