Golang reflect.Index()函数及示例
Go语言提供内置支持运行时反射的功能,并使用reflect包允许程序操作任意类型的对象。 Golang中的 reflect.Index() 函数用于获取v的第i个元素。 要访问此函数,需要在程序中导入reflect包。
语法:
func(v Value)Index(i int)Value
参数: 此函数不接受任何参数。
返回值: 此函数返回v的第i个元素。
以下示例说明了在Golang中使用上述方法的用法:
示例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))
}
}
}
输出:
Geeks1
Geeks2
Geeks3
1
2
3
示例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}))
}
输出:
[5 3 2 4 3 2 1]
极客教程