jeudi 5 janvier 2017

How to iterate over different structs in Go?

i'm stuck. I can't find out how to iterate over various structs in order to work with them. For example:

i have 2 different struct types.

package models

// User model
type User struct {
ID    int64  `db:"primary notnull unique"`
Email string `db:"notnull unique"`
}

// Article model
type Article struct {
ID    int64  `db:"primary notnull unique"`
Title string `db:"notnull unique"`
}

Now i want to iterate over those structs in a loop and do

s := models.MYSTRUCT{}
st := reflect.TypeOf(s)
field := st.Field(0)
fmt.Println(field.Tag.Get("db"))

Where "MYSTRUCT" should be replaced by the according struct, f.e. models.User{}.

At the moment i'm getting the filenames/struct-names from my "models" folder and put them into a slice, so i have

[]modelnames{"User","Article"}

And now i need to

for i:=0;i<len(modelnames);i++ {
s := models.modelnames[i]{}
st := reflect.TypeOf(s)
field := st.Field(0)
fmt.Println(field.Tag.Get("db"))
}

Where "models.modelnames[i]{}" doesn't work of course.

How do i manage this?

Regards





Aucun commentaire:

Enregistrer un commentaire