douying7289 2016-11-03 19:43
浏览 139
已采纳

Golang-具有多种输入类型的功能

I'm brand new to go and can't figure out how to do something pretty basic. Let's say that I have the following two structs:

type FooStructOld struct {
    foo1, foo2, foo3 int
}

type FooStructNew struct {
    foo1, foo2 int
}

I then want to have a function that updates the input. For example for a single type:

func updateval(arg *FooStructOld) {
    arg.foo1 = 1
}

This works as expected. However I would like the function updateval to take either FooStructOld or FooStructNew as an input. I know that I should be using an interface type but I can't quite get it to work. For example, when I try the following:

I get this error:

arg.foo1 undefined (type interface {} is interface with no methods)
cannot assign interface {} to a (type *FooStructOld) in multiple assignment: need type assertion

Does anyone know a solution for this?

  • 写回答

1条回答 默认 最新

  • douhan1860 2016-11-03 19:51
    关注

    You can either use a type assertion to extract the value from an interface{}

    func updateval(arg interface{}) {
        switch arg := arg.(type) {
        case *FooStructOld:
            arg.foo1 = 1
        case *FooStructNew:
            arg.foo1 = 1
        }
    }
    

    Or you could implement an interface that does the update

    type FooUpdater interface {
        UpdateFoo()
    }
    
    type FooStructOld struct {
        foo1, foo2, foo3 int
    }
    
    func (f *FooStructOld) UpdateFoo() {
        f.foo1 = 1
    }
    
    type FooStructNew struct {
        foo1, foo2 int
    }
    
    func (f *FooStructNew) UpdateFoo() {
        f.foo1 = 1
    }
    
    func updateval(arg FooUpdater) {
        arg.UpdateFoo()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作