英文:
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
可以接受FooStructOld
或FooStructNew
作为输入。我知道应该使用接口类型,但是我无法完全搞清楚如何实现。例如,当我尝试以下操作时:
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()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论