Multi-Sequence Switch

Is it possible to use a switch for multiple values?

Something like this:

switch(elem1, elem2, ...) {
    1 | 2 | ... => ...,
    
    1, 2 | 3, 4 | ... => ...,
    
    else => ...,
}

If you are asking if the match prongs can have multiple values, yes, the docs have some examples.

However as far as I understand, Zig switch statements are not structural pattern matching statments you see in other langs like Ocaml, Rust etc. You can’t match on the structure of a value. What you can do is Match on a Tagged Union and then use the payload value.


test "switch on tagged union" {
    const Point = struct {
        x: u8,
        y: u8,
    };
    const Item = union(enum) {
        a: u32,
        c: Point,
        d,
        e: u32,
    };

    var a = Item{ .c = Point{ .x = 1, .y = 2 } };

    // Switching on more complex enums is allowed.
    const b = switch (a) {
        // A capture group is allowed on a match, and will return the enum
        // value matched. If the payload types of both cases are the same
        // they can be put into the same switch prong.
        Item.a, Item.e => |item| item,

        // A reference to the matched value can be obtained using `*` syntax.
        Item.c => |*item| blk: {
            item.*.x += 1;
            break :blk 6;
        },

        // No else is required if the types cases was exhaustively handled
        Item.d => 8,
    };

    try expect(b == 6);
    try expect(a.c.x == 2);
}

(Stolen from the Docs)

3 Likes

No, it is not possible.
Switch expression must have a specific type. Cannot be values and pair of values at the same time because these are different types.

1 Like

I realized that in for loops, if the lengths are the same, it’s possible to iterate over multiple values. Is it possible that in the future, this capability will be added for switches as well? That is, if the types are the same