【发布时间】:2018-05-21 01:54:09
【问题描述】:
基本上我有这个:
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 ...
}
}
}
}
}
那么,还有什么其他方法可以做到这一点?
【问题讨论】:
-
鉴于问题中的要求,需要三个循环。可以重组代码以删除嵌套,但不能消除循环。是否可以将应用程序重组为使用 map[int]person,其中 person 是具有名字、姓氏和真实字段的结构?
-
并行数组通常表明你在设计阶段做错了什么。
标签: arrays performance loops go slice