Zig 0.14.0 recently released, and one of the headline features is Labeled Switch. This is a new construct that allows Zig to implement computed gotos while still having structured control flow.
foo: switch (@as(u8, 1)) {
1 => continue :foo 2,
2 => continue :foo 3,
3 => return,
4 => {},
else => unreachable,
}
The basic idea is that there exists a new syntax to jump to another switch case directly. An equivalent in Rust could look like this (I don't care about the exact syntax).
'foo: match (1u8) {
1 => continue 'foo 2,
2 => continue 'foo 3,
3 => return,
_ => {},
}
What makes this so powerful is that the switch labels can be computed at runtime and each statement can have its own branch, leading to much better branch predictor performance. This is explained in greater detail in the codegen section.
This would be very useful for implementing bytecode instructions, FSM's, and parsers. When Zig switched their own parser to this method they saw a 13% speedup.
This would also enable Rust to achieve some of the performance Python saw in their new tail-cail interpreter without requiring guaranteed tail calls and specialized calling conventions. Currently, that level of performance can only be achieved in C (and potentially now Zig).
There is a github issue that talks more about the design and reasoning behind this.
Would this be a reasonable thing to add to Rust? From a borrow checkers perspective, this doesn't seem anymore complicated than match statement in a loop.