authorgravatar for manlio.perillo@gmail.comManlio Perillo <manlio.perillo@gmail.com> 2023-01-24 16:11:38+01:00
committergravatar for git@vexu.euVeikka Tuominen <git@vexu.eu> 2023-01-25 17:03:39+02:00
log33e5a8470615d3d422b64745f0a893c2b8f62d9a
tree6f9693b5c76e733c371ae73228c7f2ff70a06983
parent8de46d1d7d08f8ecc40f049be9889efac36a6e78

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.

1 files changed, 26 insertions(+), 3 deletions(-)

doc/langref.html.in+26-3
......@@ -6448,14 +6448,37 @@ const U = union(E) {
64486448 three,
64496449};
64506450
6451const U2 = union(enum) {
6452 a: void,
6453 b: f32,
6454
6455 fn tag(self: U2) usize {
6456 switch (self) {
6457 .a => return 1,
6458 .b => return 2,
6459 }
6460 }
6461};
6462
64516463test "coercion between unions and enums" {
64526464 var u = U{ .two = 12.34 };
6453 var e: E = u;
6465 var e: E = u; // coerce union to enum
64546466 try expect(e == E.two);
64556467
64566468 const three = E.three;
6457 var another_u: U = three;
6458 try expect(another_u == E.three);
6469 var u_2: U = three; // coerce enum to union
6470 try expect(u_2 == E.three);
6471
6472 var u_3: U = .three; // coerce enum literal to union
6473 try expect(u_3 == E.three);
6474
6475 var u_4: U2 = .a; // coerce enum literal to union with inferred enum tag type.
6476 try expect(u_4.tag() == 1);
6477
6478 // The following example is invalid.
6479 // error: coercion from enum '@TypeOf(.enum_literal)' to union 'test_coerce_unions_enum.U2' must initialize 'f32' field 'b'
6480 //var u_5: U2 = .b;
6481 //try expect(u_5.tag() == 2);
64596482}
64606483 {#code_end#}
64616484 {#see_also|union|enum#}