我想在接收 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: Call using *reflect.Value as type *main.Input 如何動態reflect.New params并呼叫func?
uj5u.com熱心網友回復:
你有一層額外的reflect.Value包裝。使用input直接作為引數。它已經是一個reflect.Value.
params := []reflect.Value{input}
https://go.dev/play/p/dpIspUFfbu0
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/404472.html
標籤:
