How to use the rune method in Go language

How to use the rune method in the Go language, many novices are not very clear about it. In order to help you solve this problem, the following editor will explain in detail for you. Those who have this need can come and learn. I hope you can gain something.

1.byte type

The byte type is an alias of uint8 , representing a byte,
2.rune type

The rune type is a basic type in the Go language. In fact, it is an alias of int32 . It is mainly used to indicate that a character type is greater than one byte and less than or equal to 4 bytes, especially Chinese characters.

Example:
![Insert picture description here](https://img-blog.csdnimg.cn/d0d20055ca4242dfb6cb53a54459d968.png Code:
Code:

import "fmt"

func main(){
    
    

	//在读程序之前读者,可以先思考这四行代码输出什么内容
	fmt.Println(string(97))//前置,输出是a
	fmt.Println(string(20320))
	temp:=[]rune{
    
    20320,22909,32,19990,30028}
	fmt.Println(string(temp))

	var str string="hello world"
	fmt.Println("byte=",[]byte(str))
	fmt.Println("byte=",[]rune(str))
	fmt.Println(str[:2])
	fmt.Println(string([]rune(str)[:2]))

	var str2 string="你好 世界"
	fmt.Println("byte=",[]byte(str2))
	fmt.Println("byte=",[]rune(str2))
	fmt.Println(str2[:2])
	fmt.Println(string([]rune(str2)[:2]))
}

Result analysis: From the above output results, we can see that 1). For English strings, no matter the type of rune or byte, the length or value of the string is the same. 2). For Chinese characters, the rune type operation is much more friendly than the byte type operation. We can directly extract the corresponding number in Chinese through the [:] operation, but the byte is garbled??.

Guess you like

Origin blog.csdn.net/weixin_42918559/article/details/125064783