Home > Backend Development > Golang > How Can I Access Keys from Go Maps with Different Value Types?

How Can I Access Keys from Go Maps with Different Value Types?

Patricia Arquette
Release: 2024-12-20 01:42:09
Original
1004 people have browsed it

How Can I Access Keys from Go Maps with Different Value Types?

Accessing Keys of Maps with Different Value Types

In Go, maps are inherently generic, but their behavior is not covariant due to the absence of generic types. This means that you may encounter scenarios where you wish to access keys of maps with different value types. An attempt to use an interface{} as the value type may seem intuitive, but it doesn't work as expected.

func main() {
    mapOne := map[string]int
    mapTwo := map[string]double
    mapThree := map[string]SomeStruct

    useKeys(mapOne)
}
func useKeys(m map[string]interface{}) {
    //something with keys here
}
Copy after login

While it's understandable to desire an elegant solution, it's necessary to acknowledge that in Go, you may need to replicate certain logic for maps with different value types.

However, if you require the flexibility to obtain keys from any map, reflection can be employed:

func useKeys(m interface{}) {
    v := reflect.ValueOf(m)
    if v.Kind() != reflect.Map {
        fmt.Println("not a map!")
        return
    }

    keys := v.MapKeys()
    fmt.Println(keys)
}
Copy after login

This approach allows you to work with maps of any type, providing access to their keys.

The above is the detailed content of How Can I Access Keys from Go Maps with Different Value Types?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template