英文:
Go correct behaviour, or compiler bug?
问题
package main
type Key struct {
stuff1 string
stuff2 []string
}
type Val struct {
}
type MyMap struct {
map1 map[Key]*Val // 编译正常!
}
func main() {
var map2 map[Key]*Val // "无效的映射键类型 Key"
}
这是正确的行为,还是Go编译器的一个错误?
我正在使用Linux x64上的go-1.1。
英文:
package main
type Key struct {
stuff1 string
stuff2 []string
}
type Val struct {
}
type MyMap struct {
map1 map[Key]*Val // compiles fine!
}
func main() {
var map2 map[Key]*Val // "invalid map key type Key"
}
Is this the correct behaviour, or a bug in go compiler?
I am using go-1.1 on Linux x64.
答案1
得分: 4
编译器是正确的。根据规范:Map Types:
> 对于键类型的操作数,比较运算符==和!=必须完全定义;因此,键类型不能是函数、映射或切片。
如果键类型是结构体,则此限制会传递应用到所有结构字段上,它们也必须遵守上述引用的规则,而
stuff2 []string
并不符合。
编辑:
关于map1
没有被标记的问题,那可能是一个bug,可能是因为MyMap
从未被引用,因此它的类型检查可能被跳过了。
英文:
The compiler is right. From the specs: Map Types:
> The comparison operators == and != must be fully defined for operands of the key type; thus the key type must not be a function, map, or slice.
This restriction applies transitively if the key type is a struct to all of the struct fields, they must obey the above quoted rule as well, which
stuff2 []string
does not.
EDIT:
What concerns map1
not being flagged, that probably is a bug, perhaps caused by MyMap never being referenced and thus it's type checking was probably skipped.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论