Skip to content

Permit expression parameter for comma-list switch case for simple values #7188

Description

@chr-1x
conststd=@import("std");
pubfnmain() void {
vard: u8='d';
switch (d) {
'a'...'c'=>|c|std.debug.print("abc ({c})\n", .{c}),
'd', 'e'=>|c|std.debug.print("de ({c})\n", .{c}),
else=>|c|std.debug.print("other ({c})\n", .{c}),
}
}
./repro_switch_capture.zig:7:22: error: switch on type 'u8' provides no expression parameter
'd', 'e' => |c| std.debug.print("de ({c})\n", c),
» zig version
0.7.0+39336fd2e

I believe that an expression parameter would be useful here as, just like in the range-of-values situation, it makes the task of figuring out which case was matched more succinct.

Zig 0.7.0 documentation demonstrates using this for a union(enum) type, so it's surprising that it doesn't work in the simpler case of a plain value:

 // 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,
};

Additionally, the error can currently be bypassed by converting one of the comma-separated cases to a trivial range:

const std = @import("std");
pub fn main() void {
var d: u8 = 'd';
switch (d) {
'a'...'c' => |c| std.debug.print("abc ({c})\n", .{c}),
'd'...'d', 'e' => |c| std.debug.print("de ({c})\n", .{c}),
else => |c| std.debug.print("other ({c})\n", .{c}),
}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugObserved behavior contradicts documented or intended behaviorstage1The process of building from source via WebAssembly and the C backend.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions