循环结构并检查嵌套以找到匹配值
Loop structs and check nested to find matching value
我有一个像这样的 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”。
预期结果是 return 数据与 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()
}
你快到了。使用 FieldByName 钻取类型字段:
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()
}
我有一个像这样的 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”。
预期结果是 return 数据与 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()
}
你快到了。使用 FieldByName 钻取类型字段:
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()
}