string和byte的相互转换
package main import ( "fmt" ) func main() { ch1 := 'a' ch2 := 'b' fmt.Printf("ch1的类型是: %T, ch2的类型是: %T\n", ch1,ch2) fmt.Printf("ch1的数值是: %c, ch2的数值是: %c\n", ch1,ch2) // byte 转换为 字符串⬇️ str1 := string(ch1) str2 := string(ch2) fmt.Printf("str1的类型是: %T, str2的类型是: %T\n", str1,str2) fmt.Printf("str1的数值是: %s, str2的数值是: %s\n", str1,str2) // 字符串 转换为 byte⬇️ ch3 := str1[0] ch4 := str2[0] fmt.Printf("ch3的类型是: %T, ch4的类型是: %T\n", ch3,ch4) fmt.Printf("ch3的数值是: %c, ch4的数值是: %c\n", ch3,ch4) /* 注⚠️:byte(str1) 不能把字符串转成单个 byte:byte 只能存一个字节,而字符串可能包含多个字节 'a' 是字符字面量,不是 byte。用 ch1 := 'a' 声明时,Go 将它推断为 rune;rune 是 int32 的别名,所以 %T 输出 int32。 如果想让 ch1 是 byte,可以写 ch1 := byte('a')。而 main.go:20 中的 str1[0] 取的是字符串的第 一个字节,所以 ch3 的类型是 uint8(byte 的别名)。 */ }