英文:
Why does typecasting a single byte to string not work in go?
问题
我正在尝试将一个单字节值转换为字符串在golang中。当我将一个字节类型转换为字符串,例如string(byte)
并打印值时,我得到的响应是"{\""
。我阅读了其他答案,正确的将字节转换为字符串的方法应该是strconv.Itoa(int(bytevalue))
。为什么前者不起作用,而后者的方法是正确的呢?
英文:
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.
答案1
得分: 2
表达式string(bytevalue)
是一种转换,而不是类型转换。
规范中对于从数值类型到字符串的转换有如下说明:
将有符号或无符号整数值转换为字符串类型会产生一个包含整数的UTF-8表示的字符串。
表达式string(byte(123))
的结果是字符串"{"
,因为{
是表示符文123的UTF-8表示的字符串。
使用strconv包来获取字节的十进制表示。表达式strconv.Itoa(int(byte(123)))
的结果是字符串"123"
。
英文:
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"
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论