I have encountered an issue while working with generics in Go. Specifically, when I try to move the value type (V
) of a map to the parameter side of a generic function signature, I encountered an error (as in case 2 below).
This seems to behave differently from when I statically specify V as a string (case 3). Can someone explain why generics behave this way internally?
- func getKeys[K comparable, V any](m map[K]V) K // success
- func getKeys[K comparable](m map[K]any) K // failed
- func getKeys[K comparable](m map[K]string) K // success
/prog.go:16:10: type map\[string\]string of tickers does not match inferred type map\[string\]any for map\[K\]any
package main
func getKeys[K comparable](m map[K]any) []K { // function signature here!
var keys []K
for k := range m {
keys = append(keys, k)
}
return keys
}
func main() {
tickers := map[string]string{
"1": "1",
}
getKeys(tickers)
}