Home  >  Article  >  Backend Development  >  Return top-level keys from map using generic type parameters

Return top-level keys from map using generic type parameters

WBOY
WBOYforward
2024-02-08 20:42:18417browse

Return top-level keys from map using generic type parameters

Question content

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.


Correct answer


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
}

https://www.php.cn/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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete