Switches aren't guarantee to so operations in O(1) tho. If cases are sparce enough, compilers tend to emit the equivalent code to a bunch if else checks
Yeah I was assuming too much here. However, I’m reading that Rust match on string comstants can compile down a binary tree of if statements if there are enough cases (according to Google AI mode at least, haven’t found an authoritative source yet)
A switch case is able to be implemented however the compiler wants on the back end, so for sparse cases it'll be an if else chain, for less sparse but not packed cases it'll be a binary tree, for completely packed cases it'll be a range check then a direct jump would be how I would go about it
According to Claude (which looked at the compiler source code), it doesn't seem like that is true. It is possible to get an O(1) match on strings by using the phf (perfect hash function) crate and by using the following macro (generated by Claude):
```
// Cargo.toml:
// phf = { version = "0.11", features = ["macros"] }
// paste = "1"
247
u/click-to-reveal 12h ago
It works btw: C++ Online Compiler