Go 表达式中没有基本类型的自动转换。请参阅https://talks.golang.org/2012/goforc.slide#18。A byte
(的别名uint8
)或[]byte
([]uint8
)必须设置为布尔值、数字或字符串。
package main
import (
. "fmt"
)
func main() {
b := []byte{'G', 'o'}
c := []interface{}{b[0], float64(b[0]), int(b[0]), rune(b[0]), string(b[0]), Sprintf("%s", b), b[0] != 0}
checkType(c)
}
func checkType(s []interface{}) {
for k, _ := range s {
// uint8 71, float64 71, int 71, int32 71, string G, string Go, bool true
Printf("%T %v\n", s[k], s[k])
}
}
Sprintf("%s", b)
可用于转换[]byte{'G', 'o' }
为字符串“Go”。您可以使用 . 将任何 int 类型转换为字符串Sprintf
。请参阅https://stackoverflow.com/a/41074199/12817546。
但是Sprintf
使用反射。请参阅https://stackoverflow.com/a/22626531/12817546中的评论。使用Itoa
(Integer to ASCII) 更快。请参阅@DenysSéguret 和https://stackoverflow.com/a/38077508/12817546。行情已编辑。