【发布时间】:2022-01-06 04:33:33
【问题描述】:
我想在接收 http 调用时使用普通函数而不是 HttpHandler 所以我应该动态新参数来调用函数。
package main
import (
"fmt"
"reflect"
)
func main() {
invoke(test)
}
func invoke(function interface{}) {
funcType := reflect.TypeOf(function)
if funcType.Kind() == reflect.Func {
paramType := funcType.In(0).Elem()
input := reflect.New(paramType)
input.Elem().Field(0).SetString("neason")
input.Elem().Field(1).SetInt(18)
fmt.Println(input)
funcValue := reflect.ValueOf(function)
params := []reflect.Value{
reflect.ValueOf(input),
}
funcValue.Call(params)
}
}
type Input struct {
Name string
Age int
}
type Output struct {
Name string
Age int
}
func test(input *Input) Output {
return Output{
Name: input.Name,
Age: input.Age,
}
}
它会恐慌:反射:使用 *reflect.Value 作为类型 *main.Input 调用 如何动态reflect.New参数并调用func?
【问题讨论】: