【问题标题】:how to dynamic reflect.New params and call the func?如何动态反射。新参数并调用函数?
【发布时间】:2022-01-06 04:33:33
【问题描述】:

我想在接收 http 调用时使用普通函数而不是 HttpHandler 所以我应该动态新参数来调用函数。

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.Input 调用 如何动态reflect.New参数并调用func?

【问题讨论】:

    标签: go reflect


    【解决方案1】:

    你有一个额外的reflect.Value 包装层。直接使用input作为参数。已经是reflect.Value

        params := []reflect.Value{input}
    

    https://go.dev/play/p/dpIspUFfbu0

    【讨论】:

      猜你喜欢
      • 2016-02-07
      • 1970-01-01
      • 2013-07-24
      • 1970-01-01
      • 2021-09-09
      • 1970-01-01
      • 2011-01-13
      相关资源
      最近更新 更多