3 ms·
The Rust approach of having all indexing being unsigned has been extremely annoying for programming algorithms which need to do interesting indexing patterns li
by joppy 5y ago
The Rust approach of having all indexing being unsigned has been extremely annoying for programming algorithms which need to do interesting indexing patterns like walking backwards through an array while indexing into another: the fact that “i >= 0” can no longer be used as a loop condition is quite exasperating. It means other more complicated indexing or looping approaches need to be used, and when showing code to coworkers (mostly mathematicians), they puzzle over this for a while before asking “why not just use i >= 0”? It’s not just this case - doing index arithmetic in general is vastly complicated by the fact that it’s difficult to detect idx < 0.
I think unsignedness on array indices is one of those places where the “make invalid states unrepresentable” mantra has gone too far: yes it’s nice that theoretically the whole 64-bit index space is addressable from a byte array based at 0, but in reality -1 is just as stupid and invalid an array index as 2^64 - 1 for pretty much every use-case. What we gain is negligible; what we lose is a lot of sensible code for dealing with index arithmetic.
- jstimpfle 5y agonegative indexing could even make sense in some situations. It's not at a far stretch to imagine a pointer pointing to the one-past-last element of a series, and use e.g. -1 to get the most recent element. Python's indexing indeed works like that way.