| 1 | const FileOpenError0 = error{ |
| 2 | AccessDenied, |
| 3 | OutOfMemory, |
| 4 | FileNotFound, |
| 5 | }; |
| 6 | |
| 7 | fn openFile0() FileOpenError0 { |
| 8 | return error.OutOfMemory; |
| 9 | } |
| 10 | |
| 11 | test "unreachable else prong" { |
| 12 | switch (openFile0()) { |
| 13 | error.AccessDenied, error.FileNotFound => |e| return e, |
| 14 | error.OutOfMemory => {}, |
| 15 | // 'openFile0' cannot return any more errors, so an 'else' prong would be |
| 16 | // statically known to be unreachable. Nonetheless, in this case, adding |
| 17 | // one does not raise an "unreachable else prong" compile error: |
| 18 | else => unreachable, |
| 19 | } |
| 20 | |
| 21 | // Allowed unreachable else prongs are: |
| 22 | // `else => unreachable,` |
| 23 | // `else => return,` |
| 24 | // `else => |e| return e,` (where `e` is any identifier) |
| 25 | } |
| 26 | |
| 27 | const FileOpenError1 = error{ |
| 28 | AccessDenied, |
| 29 | SystemResources, |
| 30 | FileNotFound, |
| 31 | }; |
| 32 | |
| 33 | fn openFile1() FileOpenError1 { |
| 34 | return error.SystemResources; |
| 35 | } |
| 36 | |
| 37 | fn openFileGeneric(comptime kind: u1) switch (kind) { |
| 38 | 0 => FileOpenError0, |
| 39 | 1 => FileOpenError1, |
| 40 | } { |
| 41 | return switch (kind) { |
| 42 | 0 => openFile0(), |
| 43 | 1 => openFile1(), |
| 44 | }; |
| 45 | } |
| 46 | |
| 47 | test "comptime unreachable errors not in error set" { |
| 48 | switch (openFileGeneric(1)) { |
| 49 | error.AccessDenied, error.FileNotFound => |e| return e, |
| 50 | error.OutOfMemory => comptime unreachable, // not in `FileOpenError1`! |
| 51 | error.SystemResources => {}, |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | // test |