package main
import (
"fmt"
)
type Item struct {
Name string
Value int
}
func combineDuplicates(items []Item) []Item {
// Use a map with string keys (Name)
itemMap := make(map[string]Item)
for _, item := range items {
if existing, found := itemMap[item.Name]; found {
// Merge logic: sum values
existing.Value += item.Value
itemMap[item.Name] = existing
} else {
// Add new unique item
itemMap[item.Name] = item
}
}
// Convert map back to slice
result := make([]Item, 0, len(itemMap))
for _, item := range itemMap {
result = append(result, item)
}
return result
}
func main() {
items := []Item{
{Name: "A", Value: 10},
{Name: "B", Value: 20},
{Name: "A", Value: 15},
{Name: "C", Value: 30},
{Name: "B", Value: 25},
}
combinedItems := combineDuplicates(items)
fmt.Println("Combined Items:")
for _, item := range combinedItems {
fmt.Printf("Name: %s, Value: %d\n", item.Name, item.Value)
}
}
// Reassigning
Why is reassignment necessary?
In Go, when you access a struct value from a map like this:
You are getting a copy of the struct, not a reference.
If you modify existing.Value, it only affects the local copy, not the original struct in the map.
To actually update the map entry, you need to explicitly reassign the modified struct back:
itemMap[item.Name] = existing
No comments:
Post a Comment