There are no automatic conversions of basic types in Go expressions. See https://talks.golang.org/2012/goforc.slide#18. A byte
(an alias of uint8
) or []byte
([]uint8
) has to be set to a bool, number or string.
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)
can be used to convert []byte{'G', 'o' }
to the string "Go". You can convert any int type to a string with Sprintf
. See https://mcmap.net/q/56918/-string-to-number-conversion-in-golang.
But Sprintf
uses reflection. See the comment in https://mcmap.net/q/53864/-how-to-convert-an-int-value-to-string-in-go. Using Itoa
(Integer to ASCII) is faster. See @DenysSéguret and https://mcmap.net/q/53864/-how-to-convert-an-int-value-to-string-in-go. Quotes edited.
string(u)
orfmt.Sprintf("%s", u)
to set[]uint8
to a sting. See https://mcmap.net/q/56302/-how-to-convert-uint8-to-string.[]uint8("abc")
to set a string to[]uint8
. See https://mcmap.net/q/55268/-how-can-i-convert-string-to-integer-in-golang. – Jeaninejeanlouis