In my program I got 2 models:
type User struct {
Name string
}
type Article struct {
Title string
}
And I got arrays of data of these structs:
users := []User
articles := []Article
I'm trying to iterate over both of them at the same piece of code:
models := [][]interface{} {users, articles}
for _, model := range models {
log.Printf("%#v", model)
}
But I'm receiving an error:
cannot use users (type []User) as type []interface {} in array element
What am I doing wrong?
You should use []interface{}
instead of [][]interface{}
Try it on the go playground
If you want to iterate all structs in your inner arrays, you need to cast them to the proper type and then iterate, like this:
for _, model := range models {
if u, ok := model.([]User); ok {
for _, innerUser := range u {
log.Printf("%#v", innerUser)
}
}
if a, ok := model.([]Article); ok {
for _, innerArticle := range a {
log.Printf("%#v", innerArticle)
}
}
}
Try it on the go playground
How about using interfaces to solve your problem? you can even use the default fmt.Stringer
interface, used by fmt.Prtinf
and other standard methods.
Example:
package main
import "log"
import "fmt"
type User struct {
Name string
}
type Article struct {
Title string
}
func (art Article) String() string {
return art.Title
}
func (user User) String() string {
return user.Name
}
func main() {
models := []interface{}{User{"user1"}, User{"user2"}, Article{"article1"}, Article{"article2"}}
for _, model := range models {
printable := model.(fmt.Stringer)
log.Printf("%s
", printable)
}
}
Playground: https://play.golang.org/p/W3qakrMfOd
Maybe I'm not getting your requirements, but what's wrong with just
models := []interface{} {users, articles}
for _, model := range models {
log.Printf("%#v
", model)
}