golang rune类型简介

定义

rune关键字,它是int32的别名(-231~231-1),对于byte(-128~127),可表示的字符更多。

官方的解释如下:

// 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

实例

package main

import (
    "fmt"
    "unicode/utf8"
)

func main() {
    var chinese = "我是中国人, I am Chinese"
    fmt.Println("chinese length", len(chinese))
    fmt.Println("chinese word length", len([]rune(chinese)))
    fmt.Println("chinese word length", utf8.RuneCountInString(chinese))
}

输出:

// 注意在golang中一个汉字占3个byte
chinese length 31
chinese word length 19
chinese word length 19

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

如果我们预期想得到一个字符串的长度,而不是字符串底层占得字节长度,该怎么办呢,实例如下:

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)))
}

输出结果:

golang rune类型简介_第1张图片

 

 

你可能感兴趣的:(golang rune类型简介)