【问题标题】:Why does golang allow named slice type assignment without explicit type conversion?为什么 golang 允许命名切片类型赋值而无需显式类型转换?
【发布时间】:2016-08-02 00:11:43
【问题描述】:

我认为 go 不允许任何命名类型在没有显式类型转换的情况下进行实际类型分配。

但是如果我将[]byte 分配给json.RawMessage,它如何编译而不出错?

var a json.RawMessage // type RawMessage []byte
var b []byte

a = b

var x time.Duration // type Duration int64
var y int64

x = y // ERROR: cannot use y (type int64) as type time.Duration in assignment

https://play.golang.org/p/oD5LwJl7an

【问题讨论】:

  • 因为 int 是命名类型,而 array 是未命名类型。见stackoverflow.com/questions/19334542/…
  • @LibertyLocked int64 是命名类型吗?它背后的实际类型是什么?
  • 字节数组是由现有类型byte组成的,而byte本身是一个类型文字,不是由任何现有类型组成的

标签: go


【解决方案1】:

int64 是命名类型,[]byte 是未命名类型。

命名类型由(可能是限定的)类型名称指定;未命名类型使用类型文字指定,该类型文字由现有类型组成新类型 - golang spec

还有

如果它们的类型名称源自同一个 TypeSpec,则两个命名类型是相同的。命名类型和未命名类型总是不同的。如果对应的类型文字相同,即如果它们具有相同的文字结构并且对应的组件具有相同的类型,则两个未命名类型是相同的。 - golang spec

因此

type MyByteArray []byte
type MyInt int

var a MyByteArray
var b []byte
a = b // legal because array is unnamed - their corresponding type literals are identical

var x MyInt
var y int
x = y // illegal because int is named - they don't originate in the same type spec

另见Why can I type alias functions and use them without casting?

【讨论】:

    猜你喜欢
    • 2020-08-29
    • 1970-01-01
    • 2016-01-30
    • 2016-07-12
    • 1970-01-01
    • 1970-01-01
    • 2021-10-09
    • 2015-03-12
    • 1970-01-01
    相关资源
    最近更新 更多