【问题标题】:In golang, why does `a := []int32("hello")` work but not `a := []int("hello")`?在 golang 中,为什么 `a := []int32("hello")` 有效,但 `a := []int("hello")` 无效?
【发布时间】:2017-12-13 07:38:29
【问题描述】:

瓷砖是我的问题。在 Go 中,为什么 a := []int32("hello") 可以工作,而 a := []int("hello") 不行?

【问题讨论】:

    标签: string go type-conversion slice


    【解决方案1】:

    因为规范允许将string 值转换为rune 切片([]rune),而runealiasint32(它们是一回事)。这是第一个conversion 确实:

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

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

    并且规范不允许将string 转换为int 切片,因此第二个是编译时错误。

    【讨论】:

    • 知道了。非常感谢。所以这一切都归功于规范。
    猜你喜欢
    • 1970-01-01
    • 2014-06-18
    • 2015-11-10
    • 2010-11-05
    • 2011-11-10
    • 1970-01-01
    • 1970-01-01
    • 2010-12-16
    相关资源
    最近更新 更多