在看本篇文章之前,建议先了解一下字符编码的知识,这里推荐两篇大神写的文章
字符编码笔记: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