My problem is, I have the specified app:
myapp
|- app/main.go
|- data/a.go
|- data/b.go
In a.go I have struct with methods
package data
type A struct {
Field_a string
Field_b string
}
func (a A) SomeMethod() string {
return "somemethod A"
}
In b.go similar:
package data
type B struct {
Field_a string
Field_b string
}
func (b B) SomeMethod() string {
return "somemethod B"
}
Now I'm refering in main.go in such manner:
package main
import (
"fmt"
"myapp/data"
)
func main() {
a := data.A{"x","y"} // it works
b := data.B{"x","y"} // works as well
c := data.A{"x","y"}.SomeMethod() // works
d := data.B{"x","y"}.SomeMethod() // works too
fmt.Printf("a: %T
",a)
fmt.Printf("b: %T
",b)
fmt.Printf("c: %T
",c)
fmt.Printf("d: %T
",d)
}
But the problem which I have is that I want to iterate over these structs from package data and I've tried the following approach:
structPool := []struct{
fielda string
fieldb string
}{
data.A{"x","y"}, // data.A{"x","y"}.SometMethod() is valid at this point
data.B{"x","y"}, // data.B{"x","y"}.SometMethod() is valid at this point
}
for _, structObj := range structPool {
// can't use here structObj.SomeMethod() - why?
}
And I also tried to inititialize this slice structPool
like this: []interface{}
or []struct{}
etc but still compiler does not see methods from these packages inside for
loop. :(
I will be highly appreciated for any clues. Thank in advance
First of all, what you have done has created a new array with field fielda
and fieldb
. Its has nothing to do with your structure A
and B
. So basically you can't call method someMethod()
.
structPool = []struct {
fielda string
fieldb string
}{}
You need to implement interface to operate on these struct.
Define a interface like
type Common interface {
someMethod() string
}
And your structure A
and B
both has implemented this interface.
Now make array of this interface with your data of A
and B
.
structPool := []Common{
A{"x", "y"},
B{"x", "y"},
}
Iterate over this array structObj.someMethod()
Hope this will help.
See in action if necessary: playground
Another example: https://gobyexample.com/interfaces
Other reference: http://www.golangbootcamp.com/book/interfaces