【问题标题】:Loop structs and check nested to find matching value循环结构并检查嵌套以查找匹配值
【发布时间】:2020-11-16 22:11:44
【问题描述】:

我有一个像这样的 Go 结构:

type AuditStruct struct {
 UsesResponsiveImages struct {
        ID               string
        Details          struct {
            Type     string
        }
 }
 UsesWebpImages struct {
        ID               string
        Details          struct {
            Type     string
        }
 }
 FontDisplay struct {
        ID               string
        // NO Details
 }
 .. etc etc
}

我想遍历每个 Audit 子结构并检查其 Details.Type 是否等于“blah”。

预期的结果是将具有匹配 details.type 的数据返回到结果。目前正在使用反射,但无法解决。

v := reflect.ValueOf(audits)

values := make([]interface{}, v.NumField())

 for i := 0; i < v.NumField(); i++ {
   vDetails := v.Field(i).FieldByName("Details")
   // Cannot get type from vDetails.

   // Tried using values and interface but unsure how to access "type" sub value from values[i]
   values[i] = v.Field(i).Interface()
 }

【问题讨论】:

    标签: go struct interface


    【解决方案1】:

    你快到了。使用 FieldByName 深入到 Types 字段:

    for i := 0; i < v.NumField(); i++ {
        vDetails := v.Field(i).FieldByName("Details")
        if !vDetails.IsValid() {
            continue
        }
        vType := vDetails.FieldByName("Type")
        if !vType.IsValid() {
            continue
        }
        values[i] = vType.Interface()
    }
    

    Run it on the playground.

    【讨论】:

      猜你喜欢
      • 2018-02-08
      • 2017-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多