检查地图在Go中是否有重复的值

Vin*_*dri 1 go

考虑以下地图

mymap := make(map[string]string)
mymap["a"] = "one"
mymap["b"] = "two"
mymap["c"] = "one"
Run Code Online (Sandbox Code Playgroud)

如何确定值是否唯一?

一种策略是遍历地图,创建值的切片。然后遍历切片以查找重复项。有没有更好的办法?

Ami*_*pta 6

如果只需要对是否存在重复项进行判断,则无需知道哪些值是重复项或存在多少个重复项,那么用于跟踪现有值的最有效结构是具有空结构值的映射。

参见此处(为方便起见,粘贴在下面):

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
}
Run Code Online (Sandbox Code Playgroud)

  • 这是匿名空结构类型的文字。为了分解它,您可能熟悉类似“type myStruct struct{myField string};”之类的内容。x := myStruct{myField: "foo"}`. 空结构是没有字段的结构类型,因此您也可以想象类似“type emptyStruct struct{};”的内容。x := 空结构{}`。我可以内联该类型,在这种情况下它将是匿名的(即它没有名称),而不是创建显式命名的“emptyStruct”结构,如下所示:“x := struct{}{}”。您还可以使用非空结构来执行此操作,例如 `x := struct{myField string}{myField: "foo"}`。 (2认同)