go 浅析rune数据类型

mac2025-07-27  5

官方解释如下

// 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. //int32的别名,几乎在所有方面等同于int32 //它用来区分字符值和整数值 type rune = int32

example-01

package main import "fmt" func main() { var str = "hello 你好" fmt.Println("len(str):", len(str)) }

####打印结果是12 ,为什么呢?

golang中string底层是通过byte数组实现的。 中文字符在unicode下占2个字节,在utf-8编码下占3个字节, 而golang默认编码正好是utf-8。

example-02如果我们预期想得到一个字符串的长度,而不是字符串底层占得字节长度

package main import ( "fmt" "unicode/utf8" ) func main() { var str = "hello 你好" //golang中string底层是通过byte数组实现的,座椅直接求len 实际是在按字节长度计算 所以一个汉字占3个字节算了3个长度 fmt.Println("len(str):", len(str)) //以下两种都可以得到str的字符串长度 //golang中的unicode/utf8包提供了用utf-8获取长度的方法 fmt.Println("RuneCountInString:", utf8.RuneCountInString(str)) //通过rune类型处理unicode字符 fmt.Println("rune:", len([]rune(str))) }

打印结果:

len(str): 12 RuneCountInString: 8 rune: 8

总结:

byte 等同于int8,常用来处理ascii字符 rune 等同于int32,常用来处理unicode或utf-8字符

附加例子

package main import "fmt" func testModifyString() { s := "我hello world" s1 := []rune(s) fmt.Println(s1) s1[0] = 200 s1[1] = 128 s1[2] = 64 fmt.Println(s1) str := string(s1) fmt.Println(str) } func main() { testModifyString() }

打印结果:

[25105 104 101 108 108 111 32 119 111 114 108 100] [200 128 64 108 108 111 32 119 111 114 108 100] Ȁ@llo world

最新回复(0)