Go 语言提供了运行时反射的内置支持实现,并允许程序在反射包的帮助下操作任意类型的对象。 Golang 中的reflect.Indirect()函数用于获取v 指向的值,即如果v 是nil 指针,则Indirect 返回零值。如果 v 不是指针,则 Indirect 返回 v。要访问此函数,需要在程序中导入反射包。
Syntax:
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.
下面的例子说明了上述方法在 Golang 中的使用:
示例 1:
func Indirect(v Value) Value
输出:
// 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)
}
示例 2:
&val2 type : ptr
indirectI type : slice
indirectI value : [1 2 3 4]
输出:
// 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())
}