string(int), string(int32) and string([]int32) are all valid but string([]int) is invalid - what's the rationale here?

pyn*_*exj 0 string go slice rune

(I'm using Go 1.14.6.)

The following statements would all output the char a

Println(string(int(97) ) )
Println(string(int32(97) ) )
Println(string([]int32{97} ) )
Run Code Online (Sandbox Code Playgroud)

But

Println(string([]int{97} ) )
Run Code Online (Sandbox Code Playgroud)

would cause compile error

cannot convert []int literal (type []int) to type string
Run Code Online (Sandbox Code Playgroud)

The behavior is confusing to me. If it handles string(int) the same as string(int32), why it handles string([]int) different from string([]int32)?

icz*_*cza 6

rune代表一个 unicode 代码点是int32. 如此有效地string([]int32{})string([]rune{})将一段符文(类似于 a 的字符string)转换为string. 这很有用。

intis not int32nor rune,因此转换[]intstring应该是不合逻辑的,这是不明确的,因此语言规范不允许这样做。

将整数转换为string带有单个rune. 规格: 转换:

与字符串类型之间的转换

  1. 将有符号或无符号整数值转换为字符串类型会生成一个包含整数的 UTF-8 表示的字符串。超出有效 Unicode 代码点范围的值将转换为"\uFFFD".

这让许多人感到困惑,因为许多人期望转换结果是(十进制)表示为字符串。Go 作者已经认识到这一点,并已采取措施在未来将其从语言中删除和删除。在 Go 1.15 中,go vet已经警告过这种转换。Go 1.15 发行说明:Vet:

string(x) 的新警告

兽医工具现在发出警告的形式的转换string(x),其中x具有比其它的整数类型runebyte。Go 的经验表明,这种形式的许多转换错误地假设string(x)求值为整数 x 的字符串表示形式。它实际上计算为一个字符串,其中包含 的值的 UTF-8 编码x。例如,string(9786)不对字符串求值"9786";它计算为字符串"\xe2\x98\xba", 或"?"

string(x)正确使用的代码可以重写为string(rune(x)). 或者,在某些情况下,utf8.EncodeRune(buf, x)使用合适的字节切片buf进行调用可能是正确的解决方案。其他代码最有可能使用strconv.Itoafmt.Sprint

使用go test.

我们正在考虑在 Go 的未来版本中禁止转换。也就是说,当类型为或时,语言将更改为仅允许string(x)整数。这种语言更改不会向后兼容。我们正在使用此兽医检查作为更改语言的第一个试验步骤。xxrunebyte