Home > Software engineering >  Invalid map key type "identifier"
Invalid map key type "identifier"

Time:10-24

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?

CodePudding user response:

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.

CodePudding user response:

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
  • Related