Home >Backend Development >Golang >Brief analysis of rune type in golang

Brief analysis of rune type in golang

藏色散人
藏色散人forward
2021-12-01 14:28:006687browse

This article is introduced to you by the go language tutorial column about the golang rune type. I hope it will be helpful to friends in need!

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

The above is the detailed content of Brief analysis of rune type in golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete