Go語言字串淺析

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

Go語言中,字串就是一個唯讀(read-only)的,可以包含任意位元組(byte)的切片(slice)。由於Go源碼檔案都是使用UTF-8編碼的,所以直接在源碼中輸入的字串也都是用UTF-8編碼的(前提是字串裡沒有byte-level escapes,即位元組層面上的轉義)。請看下面這個例子:

package mainimport "fmt"func main() {    s := "日誌log"    fmt.Println(len(s))}

執行結果:

9

s是一個UTF-8編碼的字串,“日誌”兩個漢字各占3個位元組,所以一共是9個位元組。

再看一個例子:

package mainimport "fmt"func main() {    s:="\xFF\xFF"    fmt.Println(len(s))}

執行結果:

2

雖然0xFF不是一個合法的UTF-8編碼字元,但是因為字串可以包含任意位元組,所以s仍是一個合法的字串。

Go語言引入rune類型(實際就是int32)來表示字元(character),“日誌log”這個字串包含了5個字元,9個位元組。 可以用for range迴圈來遍曆UTF-8編碼字串的每個字元:

package mainimport "fmt"func main() {    s := "日誌log"    for index, runeValue := range s {        fmt.Printf("%#U starts at byte position %d\n", runeValue, index)    }}

執行結果:

U+65E5 '日' starts at byte position 0U+5FD7 '志' starts at byte position 3U+006C 'l' starts at byte position 6U+006F 'o' starts at byte position 7U+0067 'g' starts at byte position 8

參考資料:
Strings, bytes, runes and characters in Go。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.