Skip to content
Related Articles

Related Articles

Improve Article

reflect.Index() Function in Golang with Examples

  • Last Updated : 03 May, 2020

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.Index() Function in Golang is used to get the v’s i’th element. To access this function, one needs to imports the reflect package in the program.

Syntax:

func (v Value) Index(i int) Value

Parameters: This function does not accept any parameter.

Return Value: This function returns v’s i’th element.

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



Example 1:




// Golang program to illustrate 
// reflect.Index() Function 
   
package main 
    
import ( 
    "fmt"
    "reflect"
    
func main() {
    data := []string{"Geeks1", "Geeks2", "Geeks3"}
    test(data)
    data1 := []int{1, 2, 3}
    test(data1)
}
  
func test(t interface{}) {
    switch reflect.TypeOf(t).Kind() {
    case reflect.Slice:
        s := reflect.ValueOf(t)
          
        for i := 0; i < s.Len(); i++ {
            fmt.Println(s.Index(i))
        }
    }
}

Output:

Geeks1
Geeks2
Geeks3
1
2
3

Example 2:




// Golang program to illustrate 
// reflect.Index() Function 
   
package main
    
import (
    "fmt"
    "reflect"
)
   
func InvertSlice(args []reflect.Value) (result []reflect.Value) {
    inSlice, n := args[0], args[0].Len()
    outSlice := reflect.MakeSlice(inSlice.Type(), 0, n)
    for i := n-1; i >= 0; i-- {
  
    //Use of Index() method
        element := inSlice.Index(i)
        outSlice = reflect.Append(outSlice, element)
    }
    return []reflect.Value{outSlice}
}
   
func Bind(p interface{}, f func ([]reflect.Value) []reflect.Value) {
   
    invert := reflect.ValueOf(p).Elem()
    invert.Set(reflect.MakeFunc(invert.Type(), f))
}
   
    
// Main function
func main() {
   
    var invertInts func([]int) []int
    Bind(&invertInts, InvertSlice)
    fmt.Println(invertInts([]int{1, 2, 3, 4, 2, 3, 5}))
   
}

Output:

[5 3 2 4 3 2 1]



My Personal Notes arrow_drop_up
Recommended Articles
Page :