无效的映射键类型“identifier”

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

Invalid map key type "identifier"

问题

以下是翻译的内容:

以下是类型定义:

type tuple struct{
	key string
	value string
}

type identifier struct{
	metricName tuple
	labels []tuple
}

type value struct{
	timestamp int64
	timeSeriesValue float64  
}

type DataModel map[identifier][]value

出现错误:无效的 map 键类型 identifier

在 Go 中,struct 类型可以作为键

identifier 类型不可比较吗?

英文:

Below type definition:

type tuple struct{
	key string
	value string
}

type identifier struct{
	metricName tuple
	labels []tuple
}

type value struct{
	timestamp int64
	timeSeriesValue float64  
}

type DataModel map[identifier][]value

gives error: invalid map key type identifier

struct type can be a key in Go

Is identifier type not comparable?

答案1

得分: 2

比较运算符==和!=必须对键类型的操作数进行完全定义;因此,键类型不能是函数、映射或切片。

https://golang.org/ref/spec#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

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

So, it does not compile because a slice is a part of the struct used as a key.

答案2

得分: 2

地图键类型必须是可比较的,虽然你说的结构类型可以作为地图键,但它们仍然需要是可比较的。只有当结构体的字段是可比较的时候,结构体才是可比较的,而切片是不可比较的,所以identifier不是可比较的类型。因此,它不能作为地图键类型。

Go规范在以下两个部分中明确说明了这一点:


你最初的问题是关于identifier不可比较并且是无效的地图键类型。但是关于如何处理它的后续问题,很难仅根据你提供的代码来确定最佳方法,但我注意到指针值是可比较的,所以你可以将DataModel定义为:

type DataModel map[*identifier][]value
英文:

Map key types must be comparable, and while you're right that struct types are allowed to be map keys, they still need to be comparable. Structs are only comparable if their fields are comparable, and since slices are not comparable, identifier is not a comparable type. Thus, it can't be a map key type.

The Go spec spells this out pretty clearly in these two sections:


Your original question was about identifier not being comparable and being an invalid map key type. But as far as your follow-up question about what to do about it:

It's hard to say the best way to proceed based on just the code you have here, but I'll note that pointer values are comparable, so it may work well for you to define DataModel as

type DataModel map[*identifier][]value

huangapple
  • 本文由 发表于 2021年10月24日 04:32:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/69691847.html
匿名

发表评论

匿名网友

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

确定