go中的 string、[]rune()、[]byte()

110 阅读1分钟
  1. sting

    • string 底层是一个包含多个字节(1字节=8bit)的集合。
    • string 类型的是不可改变的
  2. string 可以被拆分为一个包含多个字节的序列,如:

str := "ben生而平凡"
fmt.Println([]byte(str))

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

[98 101 110 29983 32780 24179 20961]

我们通常说的字符是Unicode 字符。‘G’,‘o’,‘菜’,'鸟’都是一个字符。一个字符可以是只包含一个字节(像:‘G’,‘o’),也可以是包含多个字节(像:‘菜’,‘鸟’)。

  1. rune、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 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