Golang reflect.Call() 函数及示例
Go语言提供了内置支持运行时反射的实现,并通过反射包允许程序操作任意类型的对象。Golang 中的 reflect.Call() 函数用于调用具有输入参数 in 的函数 v。要使用此函数,需要在程序中导入 reflect 包。
语法:
func (v Value) Call(in []Value) []Value
参数: 此函数采用以下参数:
- in: 此参数为 []Value 类型。
返回值: 此函数以 Values 形式返回输出结果。
下面的示例说明了在 Golang 中使用上述 reflect.Call() 函数的用法:
示例1:
//在Golang程序中演示reflect.Call()函数
package main
import "fmt"
import "reflect"
type T struct {}
func (t *T) Geeks() {
fmt.Println("GeekforGeeks")
}
func main() {
var t T
// 调用Call()方法
val := reflect.ValueOf(&t).MethodByName("Geeks").Call([]reflect.Value{})
fmt.Println(val)
}
输出:
GeekforGeeks
[]
示例2:
//在Golang程序中演示reflect.Call()函数
package main
import "fmt"
import "reflect"
type T struct {}
func (t *T) Geeks() {
fmt.Println("GeekforGeeks")
}
func (t *T) Geeks1() {
fmt.Println("Golang Package :")
fmt.Println("reflect")
fmt.Println("Call()函数")
}
func main() {
var t T
var t1 T
// 调用Call()方法
reflect.ValueOf(&t).MethodByName("Geeks").Call([]reflect.Value{})
reflect.ValueOf(&t1).MethodByName("Geeks1").Call([]reflect.Value{})
}
输出:
GeekforGeeks
Golang Package:
reflect
Call()函数
极客教程