With Go's strong typing system, a function that takes a map with keys of type interface{} cannot be applied to a map with keys of type int. While Go does not currently support generics, we can implement a generic Keys function in several ways:
If we wish to preserve the type of the map, we can modify the Keys function to take a map[int]interface{} argument and explicitly convert the keys to interface{}:
func Keys(m map[int]interface{}) []interface{} { keys := make([]interface{}, len(m)) i := 0 for k := range m { keys[i] = k i++ } return keys }
Alternatively, we can use Go's reflection package to access the map's keys and convert them to interface{}. However, this approach may have performance implications:
func Keys(m interface{}) []interface{} { t := reflect.TypeOf(m) if t.Kind() != reflect.Map { panic("argument must be a map") } keys := make([]interface{}, 0) for _, key := range reflect.ValueOf(m).MapKeys() { keys = append(keys, key.Interface()) } return keys }
To avoid potential performance issues, we can define a generic helper function that converts a map[int]interface{} to a map[interface{}]interface{}:
func convertMap[K1 comparable, V1 any, K2 comparable, V2 any](m map[K1]V1) map[K2]V2 { ret := make(map[K2]V2, len(m)) for k, v := range m { ret[k.(K2)] = v.(V2) } return ret } // Keys returns the keys of the provided map. func Keys[K comparable, V any](m map[K]V) []K { keys := make([]K, len(m)) i := 0 for k := range m { keys[i] = k i++ } return keys }
With these helper functions, we can use the following code:
m2 := map[int]interface{}{ 2: "string", 3: "int", } convertedMap := convertMap(m2) result := Keys(convertedMap) fmt.Println(result)
The above is the detailed content of How to Efficiently Retrieve Keys from Maps in Go?. For more information, please follow other related articles on the PHP Chinese website!