我想在接收到 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 關注
- 95 瀏覽
添加回答
舉報
0/150
提交
取消