Why Range Over String Returns Runes, Byte by Index
According to the Go documentation and our own tests, when rang the elements obtained 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 from the definition of the string type. A string represents a sequence of ualtes 和 accing bys accessbys accessbys squence of ualtes. indexing.
另一方面,range子句用於for語句中,它允許遍歷string中的Unicode碼點。從0位元組索引開始,迭代將傳回每個UTF-8編碼碼點的第一個位元組索引,以及對應的碼點值(rune類型)。
如果您希望遍歷字串中的位元組而不是碼點,有幾個選擇:
這些替代方法提供了對位元組的直接訪問,而不會犧牲程式碼的可讀性。
以上是為什麼 Go 中的字串範圍會尋找返回符文,而索引會返回位元組?的詳細內容。更多資訊請關注PHP中文網其他相關文章!