如何动态反射。新参数并调用函数?

我想在接收到 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 ?


Cats萌萌
浏览 78回答 1
1回答

慕神8447489

你有一个额外的reflect.Value包装层。input直接作为参数使用。它已经是一个reflect.Value.    params := []reflect.Value{input}https://go.dev/play/p/dpIspUFfbu0
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go