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

本文探讨了Go语言中字符串的内部结构,包括它们如何存储UTF-8编码的文本,以及byte和rune类型的差异。通过示例展示了如何将字符串拆分为字节序列和Unicode字符序列,强调了字符在信息技术中的重要性。
摘要由CSDN通过智能技术生成

在看本篇文章之前,建议先了解一下字符编码的知识,这里推荐两篇大神写的文章

字符编码笔记: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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值