Commit 02e5cb1cd4

Vexu <git@vexu.eu>
2020-01-15 22:05:52
add non-exhaustive enum to langref
1 parent 5c2238f
Changed files (2)
doc/langref.html.in
@@ -2893,6 +2893,50 @@ test "switch using enum literals" {
 }
       {#code_end#}
       {#header_close#}
+
+      {#header_open|Non-exhaustive enum#}
+      <p>
+      A Non-exhaustive enum can be created by adding a trailing '_' field.
+      It  must specify a tag type and cannot consume every enumeration value.
+      </p>
+      <p>
+      {#link|@intToEnum#} on a non-exhaustive enum cannot fail.
+      </p>
+      <p>
+      A switch on a non-exhaustive enum can include a '_' prong with the following properties:
+      <ul>
+        <li>makes it a compile error if all the known tag names are not handled by the switch</li>
+        <li>allows omitting {#syntax#}else{#endsyntax#}</li>
+      </ul>
+      </p>
+      {#code_begin|test#}
+const std = @import("std");
+const assert = std.debug.assert;
+
+const Number = enum(u8) {
+    One,
+    Two,
+    Three,
+    _,
+};
+
+test "switch on non-exhaustive enum" {
+    const number = Number.One;
+    const result = switch (number) {
+        .One => true,
+        .Two,
+        .Three => false,
+        _ => false,
+    };
+    assert(result);
+    const is_one = switch (number) {
+        .One => true,
+        else => false,
+    };
+    assert(is_one);
+}
+      {#code_end#}
+      {#header_close#}
       {#header_close#}
 
       {#header_open|union#}
test/compile_errors.zig
@@ -10,9 +10,8 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {
         \\};
         \\const B = enum(u1) {
         \\    a,
-        \\    b,
         \\    _,
-        \\    c,
+        \\    b,
         \\};
         \\pub export fn entry() void {
         \\    _ = A;