gpt4 book ai didi

go - 如何在go中动态更改函数参数类型

转载 作者:数据小太阳 更新时间:2023-10-29 03:30:50 25 4
gpt4 key购买 nike

<分区>

我有一个程序如下。我正在尝试动态更改函数参数的类型,因为我正在使用的另一个库需要传递具有具体类型的 myMethod 签名而不是该接口(interface)来进行正确的解码。在 Go 中是否有可能动态生成一个函数或匿名函数,其参数类型是动态生成的,或者可能更改函数的参数类型?

package main

import (
"fmt"
"reflect"
)

type MyType interface {
doThis()
}

type MyType1 struct{}

func (m MyType1) doThis() {
fmt.Println("Type1 doThis")
}

type MyType2 struct{}

func (m MyType2) doThis() {
fmt.Println("Type2 doThis")
}

func myMethod(myType MyType) {
myType.doThis()
}

func main() {
fmt.Println("Hello, playground")
var type1 MyType
type1 = &MyType1{}
type1Val := reflect.TypeOf(type1)
// TODO - change myMethod signature dynamically to accept type1Val as the type
}

这是 GoPlay link

编辑:添加说明

我正在使用的库公开了一个 registerSomething(someFunc),其中 someFunc 的输入参数类型稍后将在某些解码中使用。如果输入参数类型是一个接口(interface),unmarshal 将返回一个映射。如果它是类型化结构,解码将返回类型化结构,并正确填充所有参数,因此我不必处理解码。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com