langref: improve test_coerce_unions_enums.zig

Add more coercion examples to test_coerce_unions_enums.zig in the
"Type Coercion: unions and enums" section.
This commit is contained in:
Manlio Perillo 2023-01-24 16:11:38 +01:00 committed by Veikka Tuominen
parent 8de46d1d7d
commit 33e5a84706

View File

@ -6448,14 +6448,37 @@ const U = union(E) {
three,
};
const U2 = union(enum) {
a: void,
b: f32,
fn tag(self: U2) usize {
switch (self) {
.a => return 1,
.b => return 2,
}
}
};
test "coercion between unions and enums" {
var u = U{ .two = 12.34 };
var e: E = u;
var e: E = u; // coerce union to enum
try expect(e == E.two);
const three = E.three;
var another_u: U = three;
try expect(another_u == E.three);
var u_2: U = three; // coerce enum to union
try expect(u_2 == E.three);
var u_3: U = .three; // coerce enum literal to union
try expect(u_3 == E.three);
var u_4: U2 = .a; // coerce enum literal to union with inferred enum tag type.
try expect(u_4.tag() == 1);
// The following example is invalid.
// error: coercion from enum '@TypeOf(.enum_literal)' to union 'test_coerce_unions_enum.U2' must initialize 'f32' field 'b'
//var u_5: U2 = .b;
//try expect(u_5.tag() == 2);
}
{#code_end#}
{#see_also|union|enum#}