go 语言中的rune类型

195 阅读1分钟

前言

今天看到leetcode中的golang题解,对于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

意思是runne是一个int32的缩写,习惯上来区分integer的值。

例子

func main(){

   a := "hello 师姐"
   fmt.Println(len(a))
}

此函数输出为12,直观预期结果为8。原因为

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

integer在go中长度默认为8,也就是

byte = int = int8

因此,因为utf-8需要32位表示一个字符,所以字符串如果使用runne,可以显示其本身的长度。
如果我们需要显示直观长度,可以使用。

func main(){

   a := "hello 师姐"
   fmt.Println(utf8.RuneCountInString(a))
   fmt.Println([]rune(a))
}

以上输出为8。