Home > Article > Backend Development > An article to help you understand the basics of Go language byte types
In the above article, we learned about the string type.
In Go language, the string type is basic type, which is stored in the stack and has the following structure .
As you can see, in Go, a string actually points to a continuous memory address, and the length is recorded, and the reading is done in one go.
So, as shown in the picture above, what are the names of the letters stored in the memory? ? ?
The string is composed of characters, In turn, it is also a string of characters spliced together into a string, and each character is called Byte. bytes occupy
1 byte size . Only letters and punctuation marks can be stored. And so on, Chinese cannot be saved. Of course, what should I do if I save Chinese??? There is a
rune in Go, and
byte is similar, the essence is the same as
byte, except
runeOne occupies
4 bytes.
Use
utf-8 Encoding can save Chinese and various languages.
Therefore, try to use the rune
type when processing Chinese.
Character Wrap it in single quotes '
.
Code
package main import "fmt" func main() { var a byte = 'a' fmt.Println(a) }
reason
byte
代表的是一个ASCII
码的一个字符,同理,rune
可以理解为是byte
的一个超集,向下兼容byte
。
package main import "fmt" func main() { var a rune = 'a' fmt.Println(a) }
结果:
但是rune
里面可以写中文,byte
不行。
发现了吗,打印的竟然是一个数字?这是为啥???
就拿字母a
来说,其实打印的是ASCII
对应的数字,打印的是他的十进制。
同理,字符张
也是,这里就不做例子了,因为utf-8
表太大了。
package main import "fmt" func main() { s := "我是法外狂徒,张三,hahaha" for _, r := range s { fmt.Printf("%c \n",r) } }
package main import "fmt" func main() { s := "我是法外狂徒,张三,hahaha" for i := 0; i < len(s); i++ { //中文会乱码,不推荐 fmt.Printf("%c \n",s[i]) } }
同理,字符串相当于是字节列表组成的,是不能直接修改的,想要直接修改需要打散成字节列表才行。
package main import "fmt" func main() { //只有英文的情况下 s1 := "hello world" var s1_byte_list = []byte(s1) //打散成字符列表 s1_byte_list[6] = 'F' //修改下表为6的字符为F s1 = string(s1_byte_list) //打散的字符列表在组装成字符串 fmt.Println(s1) //输出 hello 6orld //带有中文的情况 s2 := "天空好像下雨,我好像住你隔壁vay" var s2_rune_list = []rune(s2) //打散成utf-8字符列表 s2_rune_list[5] = '雪' //修改下表为5的字符为雪 s2 = string(s2_rune_list) //打散的utf8字符转字符串 fmt.Println(s2) //输出 天空好像下雪,我好像住你隔壁 }
The above is the detailed content of An article to help you understand the basics of Go language byte types. For more information, please follow other related articles on the PHP Chinese website!