duanli8391 2019-01-15 06:04
浏览 153
已采纳

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

I have a program as below. I am trying to change the type of a function argument dynamically as another library I am using requires passing myMethod signature with concrete type instead of that interface to do proper unmarshalling. Is that even possible in Go to dynamically make a function or anonymous function with argument's type generated dynamically or perhaps change the parameter type of a function?

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
}

Here is the GoPlay link

Edit: Adding clarification

The library I am using exposes a registerSomething(someFunc) where the input argument type of someFunc will be later used in some unmarshaling. If the input argument type is an interface, the unmarshal will return a map. If its a typed struct, the unmarshal will return the typed struct with all params populated correctly so I don't have to deal with unmarshaling.

  • 写回答

1条回答 默认 最新

  • duanmo5724 2019-01-15 06:53
    关注

    How to change function parameter type dynamically in go [?]

    You simply cannot. Go is statically typed.

    (Making your code run is trivial, but probably not what you want:

    type1Val := reflect.ValueOf(type1)
    myMethod(*(type1Val.Interface().(*MyType1)))
    

    and I have to admit I do not understand what you are trying to do with reflect here.)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码