先看代码

go
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
package main

import (
	"fmt"
)

func main() {
	var a = "hello world"

	var b = "中"
	fmt.Println([]rune(a))
	fmt.Println([]rune(b))
	fmt.Println([]byte(b))

}

img

go源码中的定义

go
1
2
3
4
5
6
7
8
// byte is an alias for uint8 and is equivalent to uint8 in all ways. It is
// used, by convention, to distinguish byte values from 8-bit unsigned
// integer values.
type byte = uint8

// rune is an alias for int32 and is equivalent to int32 in all ways. It is
// used, by convention, to distinguish character values from integer values.
type rune = int32

byte是uint8、rune为uint32,一个仅限于ascii码的值,一个支持更多的值。rune比byte能表达更多的数。

golang默认使用utf8编码,一个中文占用3字节,一个utf8数字占用1字节,utf8字母占用1字节