rune type in golang
In golang, rune is equivalent to int32, but is generally used for character conversion. The len() method in golang mainly calculates the length of the array.
The default storage string in golang is in utf8 format, utf8 uses variable-length byte storage, English letters are stored in single bytes, and Chinese are stored in 3 bytes, so the execution results of -1 and -2 It's 16 and 15. There are two ways in golang: utf8.RuneCountInString and []rune() to convert utf8 into 4-byte int32 storage, and then calculate the length of the int32 array.
-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) //可以判断字符是否是汉语
Result
-1 len(address): 16 -2 len(address): 15 -3 len(address): 5 -4 len(address): 5