为什么在Go语言中将单个字节进行类型转换为字符串时无法正常工作?

huangapple go评论82阅读模式
英文:

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".

huangapple
  • 本文由 发表于 2021年10月31日 09:54:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/69783419.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定