说说 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
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值