如何在Golang中为哈希图制作复合键

First, my definition of composite key - two ore more values combine to make the key. Not to confuse with composite keys in databases.

My goal is to save computed values of pow(x, y) in a hash table (x and y are integers). This is where I need ideas on how to make a key, so that given x and y, I can look it up in the hash table, to find pow(x,y).

Eg. pow(2, 3) => {key(2,3):8} Function / way to get the key(2,3) is what I want to figure out.

In general whats the best way to handle key which is a combination of multiple values, while using as a key in hash table.

Thanks

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.

Go can't make a hash of a slice of ints.

Therefore the way I would approach this is mapping a struct to a number.

Here is an example of how that could be done:

package main

import (
    "fmt"
)

type Nums struct {
    num1 int
    num2 int
}

func main() {
    powers := make(map[Nums]int)
    numbers := Nums{num1: 2, num2: 4}

    powers[numbers] = 6

    fmt.Printf("%v", powers[input])
}

I hope that helps