Why Range Over String Returns Runes, Byte by Index
According to the Go documentation and our own tests, when ranging over a string, the obtained elements are of type rune, whereas indexing into the string using str[index] yields bytes.
The core reason for this distinction stems from the definition of the string type. A string represents a sequence of bytes, and accessing individual bytes is possible through indexing.
On the other hand, the range clause is used in the for statement, It allows traversing Unicode code points in a string. Starting at 0 byte index, the iteration will return the first byte index of each UTF-8 encoded code point, and the corresponding code point value (rune type).
If you wish to iterate over the bytes in the string instead of code points, there are a few options:
These alternatives provide direct access to bytes without sacrificing code readability.
The above is the detailed content of Why Does Ranging Over a String in Go Return Runes, While Indexing Returns Bytes?. For more information, please follow other related articles on the PHP Chinese website!