chain_of_dogs
chain_of_dogs

Reputation: 89

Why does typecasting a single byte to string not work in go?

I am trying to convert a single byte value to a string in golang. When I do a typecast of a byte to string like string(byte) and print the value I get "{" in response. I read other answers that the correct way to convert a byte to string would be strconv.Itoa(int(bytevalue)). Why does the former not work and why is the latter approach correct.

Upvotes: 0

Views: 570

Answers (1)

Thundercat
Thundercat

Reputation: 120931

The expression string(bytevalue) is a conversion, not a typecast. The specification says this about conversions from numeric types to a string:

Converting a signed or unsigned integer value to a string type yields a string containing the UTF-8 representation of the integer.

The expression string(byte(123)) evaluates to the string "{" because { is the the string containing the UTF-8 representation of the rune 123.

Use the strconv package to get the decimal representation of the byte. The expression strconv.Itoa(int(byte(123))) evaluates to the string "123".

Upvotes: 2

Related Questions