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.)

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

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大