下面的型別定義:
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
給出錯誤: invalid map key type identifier
struct type 可以是 Go 中的一個鍵
是identifier型別沒有可比性?
uj5u.com熱心網友回復:
必須為鍵型別的運算元完全定義比較運算子 == 和 !=;因此鍵型別不能是函式、映射或切片
https://golang.org/ref/spec#Map_types
因此,它不會編譯,因為切片是用作鍵的結構的一部分。
uj5u.com熱心網友回復:
映射鍵型別必須是可比較的,雖然結構型別可以作為映射鍵是對的,但它們仍然需要可比較。只有當它們的欄位具有可比性時,結構才具有可比性,并且由于切片不可比較,identifier因此不是可比型別。因此,它不能是映射鍵型別。
Go 規范在這兩部分中非常清楚地說明了這一點:
- https://golang.org/ref/spec#Map_types
- https://golang.org/ref/spec#Comparison_operators
您最初的問題是關于identifier不可比較并且是無效的地圖鍵型別。但就您關于如何處理的后續問題而言:
很難說僅基于您在此處擁有的代碼進行操作的最佳方法,但我會注意到指標值是可比較的,因此將 DataModel 定義為
type DataModel map[*identifier][]value
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/334483.html
