golang map key struct hash policy

 
The easiest and most flexible way is to use a struct as the key type, including all the data you want to be part of the key, so in your case:
type Key struct {
    X, Y int
}

And that's all. Using it:

m := map[Key]int{}
m[Key{2, 2}] = 4
m[Key{2, 3}] = 8

fmt.Println("2^2 = ", m[Key{2, 2}])
fmt.Println("2^3 = ", m[Key{2, 3}])

Output (try it on the Go Playground):

2^2 =  4
2^3 =  8

Spec: Map types: You may use any types as the key where the comparison operators == and != are fully defined, and the above Key struct type fulfills this.

Spec: Comparison operators: Struct values are comparable if all their fields are comparable. Two struct values are equal if their corresponding non-blank fields are equal.

One important thing: you should not use a pointer as the key type (e.g. *Key), because comparing pointers only compares the memory address, and not the pointed values.

Also note that you could also use arrays (not slices) as key type, but arrays are not as flexible as structs. You can read more about this here: Why have arrays in Go?

This is how it would look like with arrays:

type Key [2]int

m := map[Key]int{}
m[Key{2, 2}] = 4
m[Key{2, 3}] = 8

fmt.Println("2^2 = ", m[Key{2, 2}])
fmt.Println("2^3 = ", m[Key{2, 3}])

Output is the same. Try it on the Go Playground.

 

出处:https://stackoverflow.com/questions/52348514/how-to-make-composite-key-for-a-hash-map-in-go

posted @ 2023-05-08 20:18  bf378  阅读(60)  评论(1编辑  收藏  举报