|
|
|
|
|
by cmccabe
4881 days ago
|
|
Doing m[f(a)] = b is not that much less convenient than m[a] = b. You can wrap it in a function if it seems easier. If f() seems expensive, then you should reconsider whether you should be using a (hash) map at all (or use a struct and cache the key value in there.) |
|
car54whereareu's code, which uses structs as keys doesn't seem to me as if it would work for variable length sequences given Go's types.
Your solution is what I had in mind when I said above you can concert your keys to strings. The way I see it there are two cases for m[f(a)]:
1. f is injective: this pretty much forces f to return a string, since it must return a data type that is allowed as a key and that can represent arbitrary length sequences without loss of information.
2. f is not injective: then we're using f as a hash function and we need to store the full key inside the value (i.e., m[f(a)]=pair(a,b)) so look ups can make equality checks for the key. You also need to handle f-collisions somehow (I just described disallowing keys with the same f, but that may not work for certain applications). You are basically writing your own hash table at this point.