英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论