4 ms·
The most obvious use case for length is iterating over the string and indexing it. In JS (or Go, Rust, Python) indexing and iteration is not byte based. As has
by tgv 3y ago
The most obvious use case for length is iterating over the string and indexing it. In JS (or Go, Rust, Python) indexing and iteration is not byte based. As has been said elsewhere, length depends on the context/way you use it.
- tialaramex 3y agoIn Rust you need to specify what it is you think you're going to "iterate over" in a string. You can't just "iterate over a string" because that's not a thing. You can get an iterator over the bytes in the string, with "foo".bytes() or you can get an iterator over the Unicode scalar values in the string with "foo".chars(), or you can iterate over a UTF-16 encoding of the string with "foo".encode_utf16() You can index into Rust's strings, but you need to specify slice indexes, you can't just treat this like it's a array because that's not what it is. If you wanted a slice of bytes you can have one cheaply, it's as_bytes() which is a [u8] and you can index directly into that slice as with any array of bytes, but you can't mutate that and those aren't characters, they're just bytes.