Now the problem is what happens for a struct that does not have any fields. I think it would make sense that it just returned âIndexOutOfBoundsâ in that case for any field_index:
it still doesnât compile, because ârange start value is greater than the end valueâ.
I think the only way to make it work is to add an if (fields.len == 0) return error.IndexOutOfBounds check before the switch, but this is ugly because it means I have to duplicate the error handling. Or am I missing some better solution?
I think what is needed here would be
âhalf-openâ switch ranges that are exclusive for the upper bound, so I could simply have a switch case like 0..fields.len, without the overflow
instead of the ârange start value is greater than the end valueâ compile error, ranges that are known to be empty at comptime should just be removed without an error, so that for Struct2 only the else => return error.IndexOutOfBounds prong remains and is run unconditionally.
Iâve also run into this recently and also found it kinda annoying and arbitrarily restrictive. You can use an inline for loop but in certain situations inline switch prongs are simply the preferable and more expressive choice.
But I too wish that switch ranges supported .. with exclusive endpoints (and if it was supported, I would prefer if ... was replaced with ..= because supporting both .. and ... seems like it would be an easy source of typos).
That these three pieces of code trivially do the same thing shows that the LLVM optimizer isnât consistently choosing a âmost optimizedâ version.