reflect.Indirect() Function in Golang with Examples

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.Indirect() Function in Golang is used to get the value that v points to, i.e., If v is a nil pointer, Indirect returns a zero Value. If v is not a pointer, Indirect returns v. To access this function, one needs to imports the reflect package in the program.

Syntax:

func Indirect(v Value) Value

Parameters: This function takes the following parameters:

  • v: This parameter is the value to be passed.

Return Value: This function returns the value that v points to.

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



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to illustrate
// reflect.Indirect() Function
  
package main
  
import (
    "fmt"
    "reflect"
)
  
// Main function
func main() {
     val1:= []int  {1, 2, 3, 4}             
  
     var val2 reflect.Value = reflect.ValueOf(&val1)
     fmt.Println("&val2 type : ", val2.Kind())
      
     // using the function
     indirectI := reflect.Indirect(val2)
     fmt.Println("indirectI  type : ", indirectI.Kind())
     fmt.Println("indirectI  value : ", indirectI)
  
}

chevron_right


Output:

&val2 type :  ptr
indirectI  type :  slice
indirectI  value :  [1 2 3 4]

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to illustrate
// reflect.Indirect() Function
  
package main
  
import (
    "fmt"
    "reflect"
)
  
// Main function
func main() {
     var val1 []int               
     var val2 [3]string        
     var val3 = make(map[int]string) 
  
     var val4 reflect.Value = reflect.ValueOf(&val1)
     indirectI := reflect.Indirect(val4)
     fmt.Println("val1: ", indirectI.Kind())
  
  
     var val5 reflect.Value = reflect.ValueOf(&val2)
     indirectStr := reflect.Indirect(val5)
     fmt.Println("val2 type : ", indirectStr.Kind())
  
     var val6 reflect.Value = reflect.ValueOf(&val3)
     fmt.Println("&val3 type : ", val6.Kind())
  
     indirectM := reflect.Indirect(val6)
     fmt.Println("val3 type : ", indirectM.Kind())
  
}

chevron_right


Output:

val1:  slice
val2 type :  array
&val3 type :  ptr
val3 type :  map



My Personal Notes arrow_drop_up

Small things always make you to think big

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.