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