byte

byte is an alias for uint8 and is equivalent to uint8 in all ways. It's used to distinguish byte values from 8-bit unsigned integer values. A byte has a limit of 0 - 255 in numerical range. It can represent an ASCII character.

Historically, the byte was the number of bits used to encode a singe character of text in computer and for this reason it's the smallest addressable unit of memory in many computer architectures.

The C/C++ PL defined byte as an "addressable unit of data storage large enough to hold any member of the basic character set of the execution environment".

In data transmission systems, the byte is used as a contiguous sequence of bits in a serial data stream, representing the smallest distinguished unit of data.

rune

rune is an alias for int32 and is equivalent to int32 in all ways. It's used, to distinguish character values from integer values. 1 rune = 4 bytes type rune = int32

ASCII 码只需要 7 bit 就可以完整地表示,但只能表示英文字母在内的128个字符,为了表示世界上大部分的文字系统,发明了 Unicode, 它是 ASCII 的超集,包含世界上书写系统中存在的所有字符,并为每个代码分配一个标准编号(称为 Unicode CodePoint),在 Go 语言中称之为 rune,是 int32 类型的别名。

Go 语言中,string 的底层表示是 byte (8 bit) 序列,而非 rune (32 bit) 序列。例如下面的例子中  和  使用 UTF-8 编码后各占 3 个 byte,因此 len("Go语言") 等于 8,当然我们也可以将字符串转换为 rune 序列。

fmt.Println(len("Go语言")) // 8
fmt.Println(len([]rune("Go语言"))) // 4

types

func main() {
     var a byte = 97
     var b = 98
     c := 'c'

     fmt.Println(a) // 97
     fmt.Println(b) // 98
     fmt.Println(c) // 99

     fmt.Printf("%c\\n", a) // a
     fmt.Printf("%c\\n", b) // b
     fmt.Printf("%c\\n", c) // c

     fmt.Println(reflect.TypeOf(a)) // uint8
     fmt.Println(reflect.TypeOf(b)) // int
     fmt.Println(reflect.TypeOf(c)) // int32
}

Character literals are set to rune type(int32)

string to bytes

fmt.Println([]byte("falcon")) // [102 97 108 99 111 110]
fmt.Println([]byte("čerešňa")) // [196 141 101 114 101 197 161 197 136 97]

bytes to string

data := []byte{102, 97, 108, 99, 111, 110}
fmt.Println(string(data)) // falcon