Open In App

reflect.MapIndex() Function in Golang with Examples

Last Updated : 03 May, 2020
Improve
Improve
Like Article
Like
Save
Share
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.MapIndex() Function in Golang is used to get the value associated with key in the map v. To access this function, one needs to imports the reflect package in the program.

Syntax:

func (v Value) MapIndex(key Value) Value

Parameters: This function does not accept any parameter.

Return Value: This function returns the value associated with key in the map v.

Below examples illustrate the use of the above method in Golang:

Example 1:




// Golang program to illustrate
// reflect.MapIndex() Function
    
package main
    
import (
    "fmt"
    "reflect"
)
   
func main() {
    test := map[string]interface{}{"First": "firstValue"}
    Pass(test)
}
  
// Main function
func Pass(d interface{}) {
    mydata := reflect.ValueOf(d).MapIndex(reflect.ValueOf("First"))
    fmt.Printf("Value: %+v \n", mydata.Interface())
    fmt.Printf("Kind: %+v \n", mydata.Kind())
    fmt.Printf("Kind2: %+v \n", reflect.ValueOf(mydata.Interface()).Kind())
}


Output:

Value: firstValue 
Kind: interface 
Kind2: string 

Example 2:




// Golang program to illustrate
// reflect.MapIndex() Function
    
package main
    
import (
    "fmt"
    "reflect"
)
  
type Test struct {
    Data string
}
  
func (t Test) GetData() string {
    return t.Data
}
  
type Stringer interface {
    GetData() string
}
  
// Main function
func main() {
    d := map[string]Stringer{"Geeks": Test{Data: "Null"}}
    mydata := reflect.ValueOf(d).MapIndex(reflect.ValueOf("Geeks"))
    fmt.Println(reflect.ValueOf(mydata.Interface()))
}


Output:

{Null}


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads