package main
import "fmt"
type User struct {
ID int
Name string
}
func contains(slice []any, item any, keyFunc func(any) any) bool {
for _, element := range slice {
if keyFunc(element) == keyFunc(item) {
return true
}
}
return false
}
func MergeSlices(old, new []any, keyFunc func(any) any) []any {
var merged []any
merged = append(merged, new...)
for _, item := range old {
if !contains(merged, item, keyFunc) {
merged = append(merged, item)
}
}
return merged
}
func main() {
old := []any{
User{ID: 1, Name: "a"},
User{ID: 2, Name: "b"},
}
new := []any{
User{ID: 2, Name: "c"},
User{ID: 3, Name: "d"},
}
mergedUsers := MergeSlices(old, new, func(item any) any {
return item.(User).ID
})
fmt.Printf("Merged Users:%+v", mergedUsers)
}