在golang中,为什么`a := []int32(“hello”)`可以工作,但`a := []int(“hello”)`不行呢?

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

In golang, why does `a := []int32("hello")` work but not `a := []int("hello")`?

问题

在Go语言中,为什么a := []int32("hello")可以工作,但a := []int("hello")不行呢?

英文:

The tile is my question. In Go, why does a := []int32("hello") work but not a := []int("hello")?

答案1

得分: 4

因为规范允许将string值转换为rune切片([]rune),而rune是对int32的别名(它们是相同的)。这就是第一个conversion所做的事情:

将字符串类型的值转换为符文类型的切片会产生一个包含字符串中各个Unicode码点的切片。

基本上,string => []rune的转换将UTF-8文本的字节(这是Go在内存中存储字符串的方式)解码为Unicode码点(rune)。

而规范不允许将string转换为int切片,所以第二个会在编译时出错。

英文:

Because the spec allows converting a string value to a rune slice ([]rune), and rune is an alias to int32 (they are one and the same). This is what the first conversion
does:

> Converting a value of a string type to a slice of runes type yields a slice containing the individual Unicode code points of the string.

Basically a string => []rune conversion decodes the UTF-8 bytes of the text (this is how Go stores strings in memory) to Unicode code points (runes).

And the spec does not allow converting a string to an int slice, so the second is a compile-time error.

huangapple
  • 本文由 发表于 2017年7月9日 22:14:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/44997314.html
匿名

发表评论

匿名网友

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

确定