Open In App

reflect.MapKeys() Function in Golang with Examples

Last Updated : 03 May, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.MapKeys() Function in Golang is used to get a slice containing all the keys present in the map, in unspecified order. To access this function, one needs to imports the reflect package in the program.
Syntax:
func (v Value) MapKeys() []Value
Parameters: This function does not accept any parameter. Return Value: This function returns a slice containing all the keys present in the map, in unspecified order.
Below examples illustrate the use of above method in Golang: Example 1: C
// Golang program to illustrate
// reflect.MapKeys() Function
  
package main
  
import (
    "fmt"
    "reflect"
)

// Main function
func main() {
    key := 10
    value := "Geeksforgeeks"

    mapType := reflect.MapOf(reflect.TypeOf(key), reflect.TypeOf(value))

    mapValue := reflect.MakeMap(mapType)
    mapValue.SetMapIndex(reflect.ValueOf(key), reflect.ValueOf(value))

    keys := mapValue.MapKeys()
    fmt.Println(keys)

}
Output:
[<int Value>]
Example 2: C
// Golang program to illustrate
// reflect.MapKeys() Function
  
package main
  
import (
    "fmt"
    "reflect"
)

// Main function
func main() {
    key := 1
    value := "abc"

    mapType := reflect.MapOf(reflect.TypeOf(key), reflect.TypeOf(value))

    mapValue := reflect.MakeMap(mapType)
    mapValue.SetMapIndex(reflect.ValueOf(key), reflect.ValueOf(value))
    mapValue.SetMapIndex(reflect.ValueOf(2), reflect.ValueOf("def"))
    mapValue.SetMapIndex(reflect.ValueOf(3), reflect.ValueOf("gh"))

    keys := mapValue.MapKeys()
    for _, k := range keys {
        c_key := k.Convert(mapValue.Type().Key())
        c_value := mapValue.MapIndex(c_key)
        fmt.Println("key :", c_key, " value:", c_value)
    }

}
Output:
key : 1  value: abc
key : 2  value: def
key : 3  value: gh

Next Article
Article Tags :

Similar Reads