go 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

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

所以当我们的字符串中包含汉字时,就要使用rune了,因为byteint8,不能完全保存utf-8编码和unicode编码,就要使用int32了,也就是rune.
下面这段代码的运行结果
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)))
}

 运行结果如下

 这位作者讲得挺好:https://www.jianshu.com/p/4fbf529926ca

 

 
posted @   逗你玩12  阅读(289)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示