代码
package main
import (
"fmt"
"reflect"
)
type Stu struct {
Name string
Age int
}
func NewStu(name string, age int) *Stu {
fmt.Println("--------")
return &Stu{Name: name, Age: age}
}
func main() {
// 获取 NewStu 函数的反射值对象
newStu := reflect.ValueOf(NewStu)
// 构造参数列表
args := []reflect.Value{reflect.ValueOf("YYDS"), reflect.ValueOf(21)}
// 调用 NewStu函数,并传递参数列表
result := newStu.Call(args)
// 获取返回值
stu := result[0].Interface().(*Stu)
// 输出结果
fmt.Println(stu)
}
运行结果
--------
&{YYDS 21}