| ... | ... | @@ -2893,6 +2893,50 @@ test "switch using enum literals" { |
| 2893 | 2893 | } |
| 2894 | 2894 | {#code_end#} |
| 2895 | 2895 | {#header_close#} |
| 2896 | |
| 2897 | {#header_open|Non-exhaustive enum#} |
| 2898 | <p> |
| 2899 | A Non-exhaustive enum can be created by adding a trailing '_' field. |
| 2900 | It must specify a tag type and cannot consume every enumeration value. |
| 2901 | </p> |
| 2902 | <p> |
| 2903 | {#link|@intToEnum#} on a non-exhaustive enum cannot fail. |
| 2904 | </p> |
| 2905 | <p> |
| 2906 | A switch on a non-exhaustive enum can include a '_' prong with the following properties: |
| 2907 | <ul> |
| 2908 | <li>makes it a compile error if all the known tag names are not handled by the switch</li> |
| 2909 | <li>allows omitting {#syntax#}else{#endsyntax#}</li> |
| 2910 | </ul> |
| 2911 | </p> |
| 2912 | {#code_begin|test#} |
| 2913 | const std = @import("std"); |
| 2914 | const assert = std.debug.assert; |
| 2915 | |
| 2916 | const Number = enum(u8) { |
| 2917 | One, |
| 2918 | Two, |
| 2919 | Three, |
| 2920 | _, |
| 2921 | }; |
| 2922 | |
| 2923 | test "switch on non-exhaustive enum" { |
| 2924 | const number = Number.One; |
| 2925 | const result = switch (number) { |
| 2926 | .One => true, |
| 2927 | .Two, |
| 2928 | .Three => false, |
| 2929 | _ => false, |
| 2930 | }; |
| 2931 | assert(result); |
| 2932 | const is_one = switch (number) { |
| 2933 | .One => true, |
| 2934 | else => false, |
| 2935 | }; |
| 2936 | assert(is_one); |
| 2937 | } |
| 2938 | {#code_end#} |
| 2939 | {#header_close#} |
| 2896 | 2940 | {#header_close#} |
| 2897 | 2941 | |
| 2898 | 2942 | {#header_open|union#} |