mirror of
https://codeberg.org/ziglang/zig.git
synced 2025-12-06 13:54:21 +00:00
add non-exhaustive enum to langref
This commit is contained in:
parent
5c2238fc4a
commit
02e5cb1cd4
2 changed files with 45 additions and 2 deletions
|
|
@ -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#}
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue