我想在接收到 http 调用时使用普通 func 而不是 HttpHandler,所以我应该动态新参数来调用 func。
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 调用。输入如何动态反射。新参数并调用 func ?
慕神8447489
相关分类