天天看點

說說 golang 中的 string、[]rune()、[]byte()

在看本篇文章之前,建議先了解一下字元編碼的知識,這裡推薦兩篇大神寫的文章

字元編碼筆記:ASCII、Unicode 和 UTF-8

字元串和編碼

string
// string is the set of all strings of 8-bit bytes, conventionally but not
// necessarily representing UTF-8-encoded text. A string may be empty, but
// not nil. Values of string type are immutable.
type string string
           
type stringStruct struct {
	str unsafe.Pointer
	len int
}
           
  • string 底層是一個包含多個位元組(1位元組=8bit)的集合。
  • string 類型的

    是不可改變的

關聯

  • string 可以被拆分為一個包含多個位元組的序列,如:
str := "ben生而平凡"
fmt.Println([]byte(str))

[98 101 110 231 148 159 232 128 140 229 185 179 229 135 161]
           
  • string 可以被拆分為一個包含多個字元的序列,如:
str := "ben生而平凡"
fmt.Println([]rune(str))

[98 101 110 29983 32780 24179 20961]
           
我們通常說的字元是

Unicode

字元。‘G’,‘o’,‘菜’,'鳥’都是一個字元。一個字元可以是隻包含一個位元組(像:‘G’,‘o’),也可以是包含多個位元組(像:‘菜’,‘鳥’)。

byte

// byte is an alias for uint8 and is equivalent to uint8 in all ways. It is
// used, by convention, to distinguish byte values from 8-bit unsigned
// integer values.
type byte = uint8
           

rune

// rune is an alias for int32 and is equivalent to int32 in all ways. It is
// used, by convention, to distinguish character values from integer values
type rune = int32
           

繼續閱讀