I have the following method which returns all keys in map
. But the parameters it accepts must be of type map[string]string
.
func GetAllKeys(m map[string]string) []string { keys := make([]string, len(m)) i := 0 for k := range m { keys[i] = k i++ } return keys }
How do I reuse this method if I have a map
but of type map[string]map[string]string
. Is there a way to generalize this method since all it would do is return the top level key from the map.
With go 1.18 you can use Type parameters:
func GetAllKeys[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 }
//m.sbmmt.com/link/3eb46aa5d93b7a5939616af91addfa88
The above is the detailed content of Return top-level keys from map using generic type parameters. For more information, please follow other related articles on the PHP Chinese website!