【问题标题】:Checking if a value exists in an array of structs within a struct检查结构中的结构数组中是否存在值
【发布时间】:2017-09-25 08:40:37
【问题描述】:

假设我有两个结构。 StructA 和 StructB,其中包含 StructA 的数组。我如何能够遍历 StructB 并检查其中的 StructA 中变量的值?

type StructA struct {
    varA string
    varB string
    varC string
}    


type StructB struct {
    foo  []StructA
}

【问题讨论】:

标签: go iteration lookup iterable


【解决方案1】:

结构在 Go 中是不可迭代的。此外,您还想遍历 foo 属性而不是多个 StructB 字段。因此,您应该遍历作为结构属性的切片。然后只需检查方程式以找到所需的值或确定它不存在。

Playground:

target := "C"
a := StructB{[]StructA{StructA{"A", "B", "C"}}}
for _, i := range a.foo {
    if target == i.varA {
        fmt.Println(i.varA)
    } else if target == i.varB {
        fmt.Println(i.varB)
    } else if target == i.varC {
        fmt.Println(i.varC)
    } else {
        fmt.Println("None of above")
    }
}

围棋非常明确,技巧很少能带来真正的利润。

【讨论】:

  • “结构在 Go 中不可迭代。”反射让我们可以遍历一个结构字段。
  • @WilliamPoussier,是的,这是真的,但是当 @j0ykls1cCMbTWfD1 有一个字段 foo 并想要遍历它时是否有帮助?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-23
  • 1970-01-01
  • 2017-03-23
  • 1970-01-01
  • 2012-05-05
  • 1970-01-01
相关资源
最近更新 更多