Return top-level keys from map using generic type parameters

WBOY
Release: 2024-02-08 20:42:18
forward
430 people have browsed it

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
}
Copy after login

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
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!