aboutsummaryrefslogtreecommitdiff
path: root/doc/langref.html.in
diff options
context:
space:
mode:
Diffstat (limited to 'doc/langref.html.in')
-rw-r--r--doc/langref.html.in29
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#}