【问题标题】:Golang reflect getting struct members in a sliceGolang反映在切片中获取结构成员
【发布时间】:2017-10-28 03:05:34
【问题描述】:

我有以下结构:

type ProductionInfo struct {
StructA []struct {
    Field1            string
    Field2            int
}

我将从 ProductionInfo 类型中的 StructA 中提取字段名称和类型。但我无法理解如何。有人可以帮帮我吗?

【问题讨论】:

    标签: go reflection struct


    【解决方案1】:

    使用反射包:

    f, _ := reflect.TypeOf(ProductionInfo{}).FieldByName("StructA")
    t := f.Type.Elem()
    for i := 0; i < t.NumField(); i++ {
        f := t.Field(i)
        fmt.Println(f.Name, f.Type)
    }
    

    【讨论】:

    • Cerise 你就是那个人.. 谢谢。我已经在使用反射,但没有使用 FieldByName。非常感谢
    猜你喜欢
    • 1970-01-01
    • 2015-04-19
    • 1970-01-01
    • 2013-09-13
    • 2014-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-04
    相关资源
    最近更新 更多