首頁 > 後端開發 > Golang > 為什麼 Go 中的字串範圍會尋找返回符文,而索引會返回位元組?

為什麼 Go 中的字串範圍會尋找返回符文,而索引會返回位元組?

Barbara Streisand
發布: 2024-12-27 20:12:32
原創
661 人瀏覽過

Why Does Ranging Over a String in Go Return Runes, While Indexing Returns Bytes?

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類型)。

如果您希望遍歷字串中的位元組而不是碼點,有幾個選擇:

  • 使用常規for循環遍歷0到len(s)-1的索引。
  • 使用for i, b := range []byte(s)將字串轉換為位元組切片,然後遍歷位元組。

這些替代方法提供了對位元組的直接訪問,而不會犧牲程式碼的可讀性。

以上是為什麼 Go 中的字串範圍會尋找返回符文,而索引會返回位元組?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板