master
 1const std = @import("std");
 2const expect = std.testing.expect;
 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 expect(e == E.two);
32
33    const three = E.three;
34    const u_2: U = three; // coerce enum to union
35    try expect(u_2 == E.three);
36
37    const u_3: U = .three; // coerce enum literal to union
38    try expect(u_3 == E.three);
39
40    const u_4: U2 = .a; // coerce enum literal to union with inferred enum tag type.
41    try expect(u_4.tag() == 1);
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 expect(u_5.tag() == 2);
47}
48
49// test