zig

fork of https://codeberg.org/ziglang/zig
Log | Files | Refs | README | LICENSE

commit 33e5a8470615d3d422b64745f0a893c2b8f62d9a (tree)
parent 8de46d1d7d08f8ecc40f049be9889efac36a6e78
Author: Manlio Perillo <manlio.perillo@gmail.com>
Date:   Tue, 24 Jan 2023 16:11:38 +0100

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.

Diffstat:
Mdoc/langref.html.in | 29++++++++++++++++++++++++++---
1 file changed, 26 insertions(+), 3 deletions(-)

diff --git a/doc/langref.html.in b/doc/langref.html.in @@ -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#}