2

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?

icza
  • 389,944
  • 63
  • 907
  • 827
WhiteAngel
  • 2,594
  • 2
  • 21
  • 35

3 Answers3

4

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

RoninDev
  • 5,446
  • 3
  • 23
  • 37
1

Maybe I'm not getting your requirements, but what's wrong with just

models := []interface{} {users, articles}
for _, model := range models {
    log.Printf("%#v\n", model)
}
newacct
  • 119,665
  • 29
  • 163
  • 224
0

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\n", printable)
    }
}

Playground: https://play.golang.org/p/W3qakrMfOd

Pablo Fernandez
  • 103,170
  • 56
  • 192
  • 232