diff options
| author | Manlio Perillo <manlio.perillo@gmail.com> | 2023-01-24 16:11:38 +0100 |
|---|---|---|
| committer | Veikka Tuominen <git@vexu.eu> | 2023-01-25 17:03:39 +0200 |
| commit | 33e5a8470615d3d422b64745f0a893c2b8f62d9a (patch) | |
| tree | 6f9693b5c76e733c371ae73228c7f2ff70a06983 /doc/langref.html.in | |
| parent | 8de46d1d7d08f8ecc40f049be9889efac36a6e78 (diff) | |
| download | zig-33e5a8470615d3d422b64745f0a893c2b8f62d9a.tar.gz zig-33e5a8470615d3d422b64745f0a893c2b8f62d9a.zip | |
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 (limited to 'doc/langref.html.in')
| -rw-r--r-- | doc/langref.html.in | 29 |
1 files changed, 26 insertions, 3 deletions
diff --git a/doc/langref.html.in b/doc/langref.html.in index 225ee48b9f..7327bbd557 100644 --- 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#} |
