查找具有相同 ID ,但其他字段值不同的结构体元素,来自两个结构体数组
时间:2024-02-13
浏览:344
作者:佚名
Golang不知道大家是否熟悉?今天我将给大家介绍《查找具有相同 ID ,但其他字段值不同的结构体元素,来自两个结构体数组》,这篇文章主要会讲到等等知识点,如果你在看完本篇文章后,有更好的建议或者发现哪里有问题,希望大家都能积极评论指出,谢谢!希望我们能一起加油进步!
问题内容
代码类似于下面:
type Contact struct {
Id string
Email string
}
type EmailDifference struct {
Id string
OldEmail string
NewEmail string
}
func main() {
ContactList1 := []Contact{
Contact{
Id: "A01",
Email: "[email protected]",
},
Contact{
Id: "A02",
Email: "[email protected]",
},
Contact{
Id: "C00",
Email: "[email protected]",
},
}
ContactList2 := []Contact{
Contact{
Id: "A01",
Email: "[email protected]",
},
Contact{
Id: "A02",
Email: "[email protected]",
},
Contact{
Id: "C00",
Email: "[email protected]",
},
}
//How to find contacts with same ID but different emails from the above 2 contact lists?
}
我需要输出一个切片 []emaildifference{},其中包含 id 相同但电子邮件地址不同的联系人。如何在不使用 2 个 for 循环的情况下高效地完成此操作(即将 contactlist1 的每个元素与 contactlist2 的所有元素进行比较,直到找到 id 中的匹配项,然后注意如果 2 封电子邮件不同则结果)?
正确答案
如果您想避免两个嵌套循环,您可以使用 map。仍然需要两个循环,但不嵌套。这是否比嵌套循环更有效,可能取决于两个列表的大小。
package main
import "fmt"
type Contact struct {
Id string
Email string
}
type EmailDifference struct {
Id string
OldEmail string
NewEmail string
}
func main() {
ContactList1 := []Contact{
Contact{
Id: "A01",
Email: "[email protected]",
},
Contact{
Id: "A02",
Email: "[email protected]",
},
Contact{
Id: "C00",
Email: "[email protected]",
},
}
ContactList2 := []Contact{
Contact{
Id: "A01",
Email: "[email protected]",
},
Contact{
Id: "A02",
Email: "[email protected]",
},
Contact{
Id: "C00",
Email: "[email protected]",
},
}
//How to find contacts with same ID but different emails from the above 2 contact lists?
var diffs []EmailDifference
// Convert ContactList2 to map
ContactEmailMap2 := make(map[string]string, len(ContactList2))
for _, c := range ContactList2 {
ContactEmailMap2[c.Id] = c.Email
}
// Loop through ContactList1
for _, c1 := range ContactList1 {
c2email, isPresent := ContactEmailMap2[c1.Id]
if isPresent && c1.Email != c2email {
diffs = append(diffs, EmailDifference{Id: c1.Id, OldEmail: c1.Email, NewEmail: c2email})
}
}
fmt.Printf("%+v", diffs)
}
今天关于《查找具有相同 ID ,但其他字段值不同的结构体元素,来自两个结构体数组》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.30
11.30
11.30
11.30
热门专题
