我想在接收到 http 调用时使用普通 func 而不是 HttpHandler,所以我应该动态新参数来调用 func。package mainimport ( "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 ?
1 回答

慕神8447489
TA贡献1780条经验 获得超1个赞
你有一个额外的reflect.Value
包装层。input
直接作为参数使用。它已经是一个reflect.Value
.
params := []reflect.Value{input}
https://go.dev/play/p/dpIspUFfbu0
- 1 回答
- 0 关注
- 77 浏览
添加回答
举报
0/150
提交
取消