2 ms·
The first is bad because of UTF-8, basically. It's unclear what an index should even return: bytes, codepoints, grapheme clusters? Furthermore, because it's a v
by steveklabnik 11y ago
The first is bad because of UTF-8, basically. It's unclear what an index should even return: bytes, codepoints, grapheme clusters? Furthermore, because it's a variable-length encoding, it's not O(1) access, which is what [] implies, and since Rust tries to surface the cost of operations, it would be inappropriate for Rust.
(Note that Rust _does_ have a ranged syntax here, which returns bytes, and is O(1))
Pre vs post increment just leads to a lot of confusion, and doesn't give you much over `x += 1`, in my opinion. Not sure what Graydon's reasoning is here.
- MrBuddyCasino 11y agoOk, thanks for the details, I suspected as much. My intuition says string indices should be accessible as grapheme clusters (and, additionally, codepoints), bytes are meaningless anyway. Whenever I want to cut and slice a string, I usually want it to be at the boundary of a letter. Yet most languages don't seem to do it this way, strangely enough.
- rspeer 11y agoWell, that's about efficiency. If you want to be able to slice at grapheme boundary n, you have to iterate through the string counting up to n to find out where it is. Might as well just provide an iterator over graphemes in the first place. You can optimize slicing on codepoint boundaries by storing strings internally in a fixed-width representation, like Python does. But now you have to convert encodings all the time just to use UTF-8 for your I/O. And that still only gets you codepoints. It's not a great tradeoff to do it that way. It wastes memory and CPU time, and randomly accessing characters of strings is just not something you actually need to do often enough to optimize for it.
- comex 11y agoJust as additional context, since this seems to come up a lot - that does not mean that UTF-8 is bad. The main alternative is UTF-32, which provides random access to codepoints rather than bytes, but since Unicode graphemes consist of multiple codepoints, UTF-32 is effectively a variable width encoding as well for most purposes, just one that uses much more memory than UTF-8 most of the time and never uses less.
- steveklabnik 11y agoOh yeah, I don't think any of this makes UTF-8 bad, in fact, I think it's the best choice. It just reveals the inherent complexity in handling string data.
- the_why_of_y 11y agoAnd UTF-16 random-access strings (like in Java and many other things designed in the 90s) make the problem even worse, because with UTF-8 you will notice the bugs as soon as the first non-English-speaker uses your system, but with UTF-16 the affected languages are a lot more obscure.