Consider the following map
mymap := make(map[string]string)
mymap["a"] = "one"
mymap["b"] = "two"
mymap["c"] = "one"
How to determine if the values are unique?
One strategy is to iterate through the map, create a slice of the values. Then iterate through the slice to find duplicates. Is there a better way?
If you just need true/false of whether there are dupes, without needing to know which values are dupes or how many dupes there are, the most efficient structure to use to track existing values is a map with empty struct values.
See here (pasted below for convenience):
package main
import (
"fmt"
)
func hasDupes(m map[string]string) bool {
x := make(map[string]struct{})
for _, v := range m {
if _, has := x[v]; has {
return true
}
x[v] = struct{}{}
}
return false
}
func main() {
mapWithDupes := make(map[string]string)
mapWithDupes["a"] = "one"
mapWithDupes["b"] = "two"
mapWithDupes["c"] = "one"
fmt.Println(hasDupes(mapWithDupes)) // prints true
mapWithoutDupes := make(map[string]string)
mapWithoutDupes["a"] = "one"
mapWithoutDupes["b"] = "two"
mapWithoutDupes["c"] = "three"
fmt.Println(hasDupes(mapWithoutDupes)) // prints false
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With