我有一个结构数组,我想删除所有重复元素,但保留数组中的最后一个元素。类似于 hashmap 的东西,我可以将每次匹配的最后一个结构更新为新数组
我有一个像这样的结构
type samplestruct struct {
value1 string
value2 string
value3 string
value4 string
value5 string
}
在我的结构数组中,如果任何结构的 value1、value2 和 value3 相同,则删除所有重复项并保留最后一个结构。
func unique(sample []samplestruct) []samplestruct {
var unique []samplestruct
for _, v := range sample {
skip := false
for _, u := range unique {
if v.value1 == u.value1 && v.value2 == u.value2 && v.value3 == u.value3 {
skip = true
break
}
}
if !skip {
unique = append(unique, v)
}
}
return unique
}
此代码返回与所提供的条件匹配的第一个结构,但我想要与条件匹配的最后一个结构
给定输入 -
[
samplestruct{"ram","rahim","india","34","india"},
samplestruct{"ram","rahim","india","38","America"},
samplestruct{"ram","rahim","india","40","Jamica"},
samplestruct{"amit","rawat","bangladesh","35","hawai"},
samplestruct{"amit","rawat","bangladesh","36","india"}
]
预期输出 -
[
samplestruct{"ram","rahim","india","40","Jamica"},
samplestruct{"amit","rawat","bangladesh","36","india"}
]
米琪卡哇伊
临摹微笑
汪汪一只猫
蛊毒传说
相关分类