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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?