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.

//int32的别名,几乎在所有方面等同于int32
//它用来区分字符值和整数值

type rune = int32

rune是Go语言中一种特殊的数据类型,它是int32的别名,几乎在所有方面等同于int32,用于区分字符值和整数值

复制代码
 1 package main
 2 
 3 import "fmt"
 4 
 5 func main() {
 6 
 7     var str = "hello 世界"
 8     fmt.Println("len(str):", len(str))
 9 
10 }
复制代码

这段代码的执行结果为:

len(str):12

从字符串字面值看len(str)的结果应该是8,但在Golang中string类型的底层是通过byte数组实现的,在unicode编码中,中文字符占两个字节,而在utf-8编码中,中文字符占三个字节而Golang的默认编码正是utf-8.

如果想要获得真实的字符串长度而不是其所占用字节数,有两种方法实现

方法一:

使用unicode/utf-8包中的RuneCountInString方法

str := "hello 世界"
fmt.Println("RuneCountInString:", utf8.RuneCountInString(str))

方法二:

将字符串转换为rune类型的数组再计算长度

str := "hello 世界"
fmt.Println("rune:", len([]rune(str)))
原文地址:https://www.cnblogs.com/qiaoyanlin/p/12077034.html