Golang reflect.Indirect() function example

package reflect

Golang reflect.Indirect() function usage example.

NOTE : Useful in a situation where you want to probe or evaluate a variable type first and then use select-case statement to handle different data type.

 package main

 import (
  "fmt"
  "reflect"
 )

 func main() {
  var i []int // slice
  var str [3]string // array
  var m = make(map[int]string) //map

  var iValue reflect.Value = reflect.ValueOf(&i)
  fmt.Println("&i type : ", iValue.Kind()) // ptr or pointer type of because &i

  indirectI := reflect.Indirect(iValue)

  fmt.Println("i type : ", indirectI.Kind())

  fmt.Println("-----------------------------------------")

  var strValue reflect.Value = reflect.ValueOf(&str)
  fmt.Println("&str type : ", strValue.Kind())

  indirectStr := reflect.Indirect(strValue)
  fmt.Println("str type : ", indirectStr.Kind())

  fmt.Println("-----------------------------------------")

  var mValue reflect.Value = reflect.ValueOf(&m)
  fmt.Println("&m type : ", mValue.Kind())

  indirectM := reflect.Indirect(mValue)

  fmt.Println("m type : ", indirectM.Kind())

 }

Output :

&i type : ptr

i type : slice


&str type : ptr

str type : array


&m type : ptr

m type : map

Reference :

http://golang.org/pkg/reflect/#Indirect

Advertisement