如何动态reflect.New params并调用func?
时间:2024-04-11
浏览:167
作者:佚名
最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《如何动态reflect.New params并调用func?》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~
问题内容
我想在接收http调用时使用普通的func而不是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 params并调用func?
正确答案
您有一个额外的 reflect.value 包装层。直接使用input作为参数。它已经是一个 reflect.value。
params := []reflect.Value{input}
https://go.dev/play/p/dpIspUFfbu0
今天关于《如何动态reflect.New params并调用func?》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
热门专题
