在阅读 go 规范“可分配性”部分时,我尝试执行几个示例以更好地理解该主题,但现在我不知道我在代码中做错了什么。
根据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
关于go - golang 规范中的可分配性问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59507320/