golang中rune类型
在golang中rune等同于int32,只是一般用于字符转换。golang中len()方法主要计算数组长度。
golang中默认存储字符串是采用utf8格式,utf8采用变长字节存储,英文字母是单字节存储,中文是3个字节存储,所以-1和-2的执行结果是16和15。golang中有utf8.RuneCountInString和[]rune()两种方式将utf8转换成4个字节的int32存储,然后计算int32数组的长度。
-1 address := "this is shanghai" fmt.Println("len(address):",len(address)) -2 address := "this is shanghai" fmt.Println("len(address):",len(address)) -3 addressThree := "这是在上海" fmt.Println("len(address):",utf8.RuneCountInString(addressThree)) -4 fmt.Println("len(address):",len([]rune(addressThree))) -5 unicode.Is(unicode.Han, c) //可以判断字符是否是汉语
结果
-1 len(address): 16 -2 len(address): 15 -3 len(address): 5 -4 len(address): 5