考虑以下地图
mymap := make(map[string]string)
mymap["a"] = "one"
mymap["b"] = "two"
mymap["c"] = "one"
如何确定值是否唯一?
一种策略是遍历地图,创建值的切片。然后遍历切片以查找重复项。有更好的方法吗?
答案 0 :(得分:5)
如果只需要对是否存在重复项进行判断,则无需知道哪些值是重复项或存在多少个重复项,用于跟踪现有值的最有效结构是具有空结构值的映射。 / p>
请参见here(为方便起见,粘贴在下面):
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
}