Just noticed I was doing something like this in a toString-like method on an enum in my app. It doesn’t really hurt anything, but it’s weird looking, and seems hoinestly like it should be invalid syntax, or at least warning-worthy. Sorry if this has been discussed before, tried searching the forum but came up empty.
It doesn’t really hurt anything, but yes, it is kind of unidiomatic to have switch prongs return when the switch itself is an expression to a return.
Allowing switch prongs to contain returns does have valid use cases, though, for “short circuiting” a function in certain cases. E.g. you couldd have something like this:
const Thing = union(enum) { a: u32, b };
fn doStuff(the: Thing) []const u8 {
const v = switch (the) {
.a => |a_value| a_value,
.b => return "Second value", // here, the function ends immediately
};
// do something more complex here with V
return some result;
}
Side note: Zig doesn’t have warnings and the goal as far as I understand is for it to never have any. If this case ever gets treated, it’ll probably become an error.
An unreachable “return” (the one returning the result of the switch statement, of which both branches return on their own instead of producing a value.)
I assume that the OP expects any unreachable code to produce a warning, which is a reasonable assumption IMO considering a lot of newer languages do that
I guess this is because of how the lazy analysis works. When all the switch prongs return early, the compiler doesn’t even look at the rest of the function. This also compiles without error:
Side-side note: there is always the possibility of a comptime causing unreachable code, e.g. on some platform, early return an error because it’s not supported. Wouldn’t make sense on that platform to annotate that “yes, this early return is meant to return early”. Analyzing more than the current comptime would be wasteful during compilation.
Maybe it would be in the domain of zls to produce that kind of warning, i.e. to consider many comptime possibilities and do some analysis on that.