add non-exhaustive enum to langref

This commit is contained in:
Vexu 2020-01-15 23:05:52 +02:00
parent 5c2238fc4a
commit 02e5cb1cd4
No known key found for this signature in database
GPG key ID: 59AEB8936E16A6AC
2 changed files with 45 additions and 2 deletions

View file

@ -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#}

View file

@ -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;