go - golang 规范中的可分配性问题

标签 go language-specifications

在阅读 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/

相关文章:

bash - go 1.5 : Is "go install" behaviour changed? 删除陈旧的可执行文件?

file - 如何创建golang热文件夹只修改一次文件

datetime - Go 的替代日期/时间库

javascript - 如何可靠地检测 JavaScript 中的外来对象?

rust - Rust 中元组的求值顺序是什么?

java - 使用静态方法更改类以在 Java 中进行接口(interface)的二进制兼容性

vba - VBA 的语法(可能是 BNF)规范?

go - select是否尝试在默认值之前发送?

Blogger 模板语言规范

go - 文件夹中没有可构建的 Go 源文件