我有一个程序如下。我正在尝试动态更改函数参数的类型,因为我正在使用的另一个库需要传递myMethod具有具体类型而不是该接口的签名才能进行正确的解组。在 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
}
我正在使用的库公开了一个registerSomething(someFunc)输入参数类型someFunc稍后将在某些解组中使用的位置。如果输入参数类型是一个接口,unmarshal 将返回一个映射。如果它是一个类型化的结构,解组将返回类型化的结构,所有参数都正确填充,所以我不必处理解组。
哈士奇WWW
BIG阳
随时随地看视频慕课网APP
相关分类