Advertisement
cydside

Find duplicates in a struct array on multiple fields

Jan 20th, 2024
963
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.78 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5. )
  6.  
  7. // Define your struct
  8. type Person struct {
  9.     Name string
  10.     Age  int
  11.     City string
  12. }
  13.  
  14. func main() {
  15.     // Create an array of structs
  16.     people := []Person{
  17.         {"John", 25, "New York"},
  18.         {"Jane", 30, "London"},
  19.         {"John", 30, "New York"},
  20.         {"Bob", 22, "Paris"},
  21.         {"Jane", 30, "London"},
  22.     }
  23.  
  24.     // Create a map to store the encountered values
  25.     seen := make(map[struct{ Name, City string }]bool)
  26.  
  27.     // Iterate through the array
  28.     for _, person := range people {
  29.         // Check if the combination of Name and City has been seen before
  30.         key := struct{ Name, City string }{person.Name, person.City}
  31.         if seen[key] {
  32.             fmt.Printf("Duplicate found: %+v\n", person)
  33.         } else {
  34.             // Mark the current combination as seen
  35.             seen[key] = true
  36.         }
  37.     }
  38. }
  39.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement