Go正确的行为,还是编译器的错误?

huangapple go评论93阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2013年6月13日 19:11:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/17085627.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定