Handling a range of unreachable values in a switch

Suppose I have a fairly large amount of possible values in a switch, and need to check a few of them for special behavior and most of them for default behavior, but I also have some values that are forbidden. Is that doable inside a switch?

switch (value) {
    0, 1, 2 => do_this(),
    3, 4, 5 => do_that(),
    unreachable_values => unreachable, // pseudo code
    else => do_default(),
}
switch (value) {
    0, 1, 2 => do_this(),
    3, 4, 5 => do_that(),
    6...std.math.maxInt(u8) => unreachable, // pseudo code
}

Are you looking for something like this?

No. In my case it is a u4 where the values 10 and 11 are impossible.
Easy to solve of course for this but I was wondering how to do it in a strange case.

The do_default() is a requirement :slight_smile:

Let’s say we have a u6 where the values 3, 6, 7, 12, 13, 14, 54, 47, 61 are invalid.
I would like to do something like this:

const unreachables: [9]u6 = .{ 3, 6, 7, 12, 13, 14, 54, 47, 61 };

switch (value) {
   1, 2 => do_this(), // valid
   11, 50, 51 => do_that(), // valid
   unreachables: unreachable, // not allowed
   else => do_default(), // valid
}
switch (value) {
   1, 2 => do_this(), // valid
   11, 50, 51 => do_that(), // valid
   3, 6, 7, 12, 13, 14, 54, 47, 61 => unreachable, // not allowed
   else => do_default(), // valid
}

or if you want to keep them in an array:

switch (value) {
    1, 2 => do_this(), // valid
    11, 50, 51 => do_that(), // valid
    else => |n| for (unreachables) |u| {
        if (n == u) break;
    } else do_default(), // valid
}

The first one is funny :slight_smile:
The idea is that the unreachables are defined somewhere else (other zig file).
The else solution is nice Thanks.
Shouldnt it be:

switch (value) {
    1, 2 => do_this(),
    11, 50, 51 => do_that(),
    else => |n| for (unreachables) |u| {
        if (n == u) unreachable; // <---
    } else do_default(),
}

It would be nice if the switch could do that himself - compilerwise.

This proposal would let you unpack an array of comptime-known values into switch prongs. It’s not formally accepted but mlugg has expressed support for it.

(However, you could also ask yourself if an array of unreachable values is really the best and most readable/debuggable way of representing your application’s logic. Don’t make things more complicated for yourself than necessary.)

2 Likes