Brief analysis of rune type in golang

藏色散人
Release: 2021-12-01 14:28:00
forward
6598 people have browsed it

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) //可以判断字符是否是汉语
Copy after login

Result

-1 
len(address): 16

-2
len(address): 15

-3
len(address): 5

-4
len(address): 5
Copy after login

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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!