检查一个值是否存在于一个包含结构体的结构体数组中。

huangapple go评论68阅读模式
英文:

Checking if a value exists in an array of structs within a struct

问题

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

type StructA struct {
    varA string
    varB string
    varC string
}

type StructB struct {
    foo []StructA
}

你可以使用以下代码来循环遍历 StructB,并检查其中的 StructA 变量的值:

for _, structA := range structB.foo {
    // 访问 StructA 的变量值
    fmt.Println(structA.varA)
    fmt.Println(structA.varB)
    fmt.Println(structA.varC)
}

在上面的代码中,structB.foo 是 StructB 中的 StructA 数组。通过使用 range 关键字,我们可以遍历该数组,并访问每个 StructA 的变量值。在循环中,你可以根据需要执行其他操作。

英文:

Supposing I have two structs. StructA, and StructB which contains an array of StructA's. How am I able to loop through a StructB and check the value of a variable in the StructA's within it?

type StructA struct {
    varA string
    varB string
    varC string
}    


type StructB struct {
    foo  []StructA
}

答案1

得分: 1

在Go语言中,结构体(Struct)是不可迭代的。此外,你想要遍历的是foo属性,而不是多个StructB字段。因此,你应该遍历结构体中的一个切片属性。然后,只需检查等式以找到所需的值,或确定其不存在。

以下是代码示例:

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语言非常明确,技巧很少能带来真正的收益。

英文:

Struct is not iterable in Go. Also you want to iterate thorough a foo attribute not through a multiple StructB fields. Therefore you should iterate through a slice which is an attribute of the struct. And then just check for equation to find a desired value or determine that it is not there.

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 is pretty explicit and tricks seldom give a real profit.

huangapple
  • 本文由 发表于 2017年4月27日 21:44:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/43659692.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定