Go 从嵌套结构获取标记

Go 从嵌套结构获取标记,go,Go,假设我有一个结构,看起来像: 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 `js

假设我有一个结构,看起来像:

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"`
    }
}
下面的代码无法从嵌套结构部门获取标记

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)
    }
}
有没有办法从嵌套结构中获取标记??谢谢。

大家好,新年快乐

您的部门子结构本身没有标签,您正试图打印它们

<>你的代码应该考虑在循环内检查的字段可以是结构本身,并相应地下降到它。

以下是标签打印机的简单递归版本:

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())
}
希望这有帮助。

大家好,新年快乐

您的部门子结构本身没有标签,您正试图打印它们

<>你的代码应该考虑在循环内检查的字段可以是结构本身,并相应地下降到它。

以下是标签打印机的简单递归版本:

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())
}

希望这有帮助。

部门结构本身没有标签,只有字段。您需要在
部门
本身的字段上循环。因为它是嵌套的,所以您需要为每个嵌套级别更深一层
NumField
仅返回调用它的类型的字段数。相应地,
Field
只返回您调用它的类型的字段,它不会返回嵌套字段。
部门
结构本身没有标记,只有字段。您需要在
部门
本身的字段上循环。因为它是嵌套的,所以您需要为每个嵌套级别更深一层
NumField
仅返回调用它的类型的字段数。相应地,
Field
只返回您调用它的类型的字段,它不会返回嵌套字段。顺便说一句,我可以得到每个字段的值吗?在上面的示例中,您正在迭代
Type
s信息。如果需要值,应该在
main
中使用
reflect.ValueOf
,并使用类似的loop.btw,我可以获得每个字段的值吗?在上面的示例中,您正在迭代
类型
的信息。如果需要值,应在
main
中使用
reflect.ValueOf
,并使用类似的循环。
column:  id
column:  first_name
column:  last_name
column:  name
column:  size