Golang – 多个输入类型的函数

huangapple go评论66阅读模式
英文:

Golang - Function with multiple input types

问题

我是你的中文翻译助手,以下是翻译好的内容:

我刚开始学习Go语言,但是无法弄清楚如何完成一些基本操作。假设我有以下两个结构体:

type FooStructOld struct {
    foo1, foo2, foo3 int
}

type FooStructNew struct {
    foo1, foo2 int
}

我想要创建一个函数来更新输入的结构体。例如,对于单个类型:

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

这个函数按预期工作。然而,我希望函数updateval可以接受FooStructOldFooStructNew作为输入。我知道应该使用接口类型,但是我无法完全搞清楚如何实现。例如,当我尝试以下操作时:

func updateval(arg interface{}) {
    arg.foo1 = 1
}

我会得到以下错误:

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

有人知道解决方法吗?

英文:

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

得分: 10

你可以使用类型断言来从interface{}中提取值。

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

或者你可以实现一个执行更新操作的接口。

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()
}
英文:

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()
}

huangapple
  • 本文由 发表于 2016年11月4日 03:43:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/40409945.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定