基本上我有这个:
package main
import "fmt"
type Struct1 struct {
id int
name string
}
type Struct2 struct {
id int
lastname string
}
type Struct3 struct {
id int
real bool
}
func main() {
var (
s1 []Struct1
s2 []Struct2
s3 []Struct3
)
s1 = append(s1, Struct1{id: 1, name: "Eliot"}, Struct1{id: 2, name: "Tyrell"}, Struct1{id: 3, name: "Mr Robot"})
s2 = append(s2, Struct2{id: 1, lastname: "Anderson"}, Struct2{id: 2, lastname: "Wellick"})
s3 = append(s3, Struct3{id: 1, real: true}, Struct3{id: 2, real: true}, Struct3{id: 3, real: false})
}
我想展示这样的东西:
- 艾略特安德森真实(真实)
- Tyrell Wellick 真实(真实)
但我不想在 s2 中循环 s1,然后在 s3 中循环
例子:
for i := 0; i < len(s1); i++ {
for j := 0; j < len(s2); j++ {
if s1[i].id == s2[j].id {
for k := 0; k < len(s3); k++ {
if s2[j].id == s3[k].id {
// some code ...
}
}
}
}
}
那么,还有哪些其他方法可以做到这一点?
最佳答案
正确的方法是将它们放在一个散列中(在 Golang 中称为 map)。这样您可以获得性能,并且只需一个循环遍历 id 即可。
这是您的示例数据的示例:
package main
import (
"fmt"
)
type Struct1 struct {
id int
name string
}
type Struct2 struct {
id int
lastname string
}
type Struct3 struct {
id int
real bool
}
func main() {
//var (
//s1 []Struct1
// s2 []Struct2
// s3 []Struct3
// )
s1Hash := make(map[int]Struct1)
s2Hash := make(map[int]Struct2)
s3Hash := make(map[int]Struct3)
s11 := Struct1{id: 1, name: "Eliot"}
s12 := Struct1{id: 2, name: "Tyrell"}
s13 := Struct1{id: 3, name: "Mr Robot"}
s1Hash[s11.id] = s11
s1Hash[s12.id] = s12
s1Hash[s13.id] = s13
s21 := Struct2{id: 1, lastname: "Anderson"}
s22 := Struct2{id: 2, lastname: "Wellick"}
s2Hash[s21.id] = s21
s2Hash[s22.id] = s22
s31 := Struct3{id: 1, real: true}
s32 := Struct3{id: 2, real: true}
s33 := Struct3{id: 3, real: false}
s3Hash[s31.id] = s31
s3Hash[s32.id] = s32
s3Hash[s33.id] = s33
//s1 = append(s1, Struct1{id: 1, name: "Eliot"}, Struct1{id: 2, name: "Tyrell"}, Struct1{id: 3, name: "Mr Robot"})
//s2 = append(s2, Struct2{id: 1, lastname: "Anderson"}, Struct2{id: 2, lastname: "Wellick"})
//s3 = append(s3, Struct3{id: 1, real: true}, Struct3{id: 2, real: true}, Struct3{id: 3, real: false})
//i to loop over possible id range
for i := 1; i <= len(s1Hash); i++ {
fmt.Println("i is ", i)
if _, ok := s1Hash[i]; ok {
fmt.Printf("Name: %s ", s1Hash[i].name)
}
if _, ok := s2Hash[i]; ok {
fmt.Printf(" Lastname: %s ", s2Hash[i].lastname)
}
if _, ok := s3Hash[i]; ok {
fmt.Printf(" Real: %t\n", s3Hash[i].real)
}
//fmt.Printf("%s %s real:%t\n", s1Hash[i].name, s2[i].lastname, s3[i].real)
}
}
输出:
i is 1
Name: Eliot Lastname: Anderson Real: true
i is 2
Name: Tyrell Lastname: Wellick Real: true
i is 3
Name: Mr Robot Real: false
检查 this在 Playground 上。希望这对您有所帮助!
附注:最终,如果您可能删除某些 ID 的所有结构条目并添加更新的 ID - 您可以考虑将有效 ID 添加到映射 map[int]bool
(mymap[id] = true
) 并使用 range
代替上面的 for i..
遍历 map 。
关于arrays - 在 go 中循环 slice/数组的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47686910/