Dynamic map keys

I need to efficiently associate uniform data (whose size and structure is unknown at compile time) with some other data whose structure is unimportant. Slices can’t be used as map keys, and arrays don’t work for my use case because the size of my keys (while uniform) isn’t known at compile time.

Basically what I want to do is this:

package main

import "fmt"

func main() {
	var x int = 3
 	key1 := [x]interface{}{1, "foo", true}
 	key2 := [x]interface{}{0, "baz", false}

	m := map[interface{}]string{key1: "key1", key2: "key2"}

	fmt.Println(m[[x]interface{}{1, "foo", true}])

Any suggestions?

Strings can, however, so if you have a []byte that is an unambiguous representation of your key, you can

var m map[string]whatever
// ...
key := []byte{1, 2, 3, 4} // or wherever the key comes from
m[string(key)] = ...
1 Like

Unfortunately, this is in the hot path, so I’m concerned about the serialization cost. I suppose this is the best case solution…

There is no serialization cost if it’s already a []byte. It will by necessity be copied but that’s both cheap and unavoidable.

It’s not already a []byte :frowning:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.