从嵌套结构获取标签

Let say I have a struct look like:

type Employee struct {
    ID        uint32    `json:"id" sql:"id"`
    FirstName string    `json:"first_name" sql:"first_name"`
    LastName  string    `json:"last_name" sql:"last_name"`
    Department struct {
        Name string `json:"name" sql:"name"`
        Size int `json:"size" sql:"size"`
    }
}

The code below can not get tags from nested struct Department

func main(){
    t := reflect.TypeOf(&Employee{}).Elem()
    for i := 0; i < t.NumField(); i++ {
        field := t.Field(i)
        column := field.Tag.Get("sql")
        fmt.Println("column: ", column)
    }
}

Result:

column:  id
column:  first_name
column:  last_name
column: 

Is there any way to get tags from nested struct ?? thanks.

Hi and Happy New Year!

Your Department sub-structure doesn't have tags itself and you were trying to print them.

Your code should consider that the field being checked inside the loop can be struct itself and descend into it accordingly.

Here's a simple recursive version of the tags printer:

func printTags(t reflect.Type) {
    for i := 0; i < t.NumField(); i++ {
        field := t.Field(i)

        if field.Type.Kind() == reflect.Struct {
            printTags(field.Type)
            continue
        }

        column := field.Tag.Get("sql")
        fmt.Println("column: ", column)
    }
}

func main() {
    printTags(reflect.TypeOf(&Employee{}).Elem())
}

Then you have the output:

column:  id
column:  first_name
column:  last_name
column:  name
column:  size

Hope this helps.