http://play.golang.org/p/BoZkHC8_uA
I want to convert uint8 to string but can't figure out how.
package main
import "fmt"
import "strconv"
func main() {
str := "Hello"
fmt.Println(str[1]) // 101
fmt.Println(strconv.Itoa(str[1]))
}
This gives me prog.go:11: cannot use str[1] (type uint8) as type int in function argument
[process exited with non-zero status]
Any idea?
Simply convert it :
There is a difference between converting it or casting it, consider:
The string cast prints '\n' (newline), the string conversion prints "10". The difference becomes clear once you regard the []byte conversion of both variants:
see this code in play.golang.orgThere are no automatic conversions of basic types in Go expressions. See https://talks.golang.org/2012/goforc.slide#18. A
byte
(an alias ofuint8
) or[]byte
([]uint8
) has to be set to a bool, number or string.Sprintf("%s", b)
can be used to convert[]byte{'G', 'o' }
to the string "Go". You can convert any int type to a string withSprintf
. See https://stackoverflow.com/a/41074199/12817546.But
Sprintf
uses reflection. See the comment in https://stackoverflow.com/a/22626531/12817546. UsingItoa
(Integer to ASCII) is faster. See @DenysSéguret and https://stackoverflow.com/a/38077508/12817546. Quotes edited.You can do it even simpler by using casting, this worked for me: