golang规范中的可分配性问题

Assignability question in golang specification

在阅读 go 规范 "Assignability" 部分时,我尝试执行几个示例以更好地理解该主题,但现在我无法理解我的代码中做错了什么。

根据 specification, 值 x 可分配给类型 T 的变量的情况之一如下:

x's type V and T have identical underlying types and at least one of V or T is not a defined type.

定义类型 specification 说明

Type definition creates a new, distinct type with the same underlying type and operations as the given type, and binds an identifier to it.

但是当我尝试 运行 以下代码时,构建失败:

func main() {
    type Defined int32
    var d Defined
    var i int32
    d = i
}

输出为:

cannot use i (type int32) as type Defined in assignment

与此同时,具有复合文字的类似示例工作正常:

func main() {
    type MyMap map[string]int
    var x MyMap 
    var y map[string]int
    x = y
}

playground

同样来自规范:

https://golang.org/ref/spec#Numeric_types

To avoid portability issues all numeric types are defined types and thus distinct

由于 type Defined int32 定义了一个新类型,di 没有相同的类型;因此,第一个子句 x 的类型与 assignability spec 中的 T 相同是不适用的。第二个子句 x 的类型 V 和 T 具有相同的基础类型,并且 V 或 T 中至少有一个不是定义的类型 不适用,因为 id 是定义的类型。由于可分配性规范中的其余条款不适用于这种情况,因此分配失败。将 type Defined int32 更改为 type Defined = int32(为类型起别名)可修复错误。

x = y 由于 T 是接口类型并且 x 实现了可分配性规范中的 T 子句。