goreflect

how to dynamic reflect.New params and call the func?


i want to use a normal func instead of a HttpHandler when receiving a http call so i should dynamic new params to call the 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,
    }
}

it will panic: reflect: Call using *reflect.Value as type *main.Input how to dynamic reflect.New params and call the func ?


Solution

  • You have an extra layer of reflect.Value wrappers. Use input directly as the parameter. It's already a reflect.Value.

        params := []reflect.Value{input}
    

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