您的方法将为每次插入花费线性时间。更好的方法是使用
map[int]struct{}。另外,您也可以使用amap[int]bool或类似名称,但是empty
struct{}的优点是它不占用任何额外空间。因此,map[int]struct{}是一组整数的普遍选择。例:
set := make(map[int]struct{})set[1] = struct{}{}set[2] = struct{}{}set[1] = struct{}{}// ...for key := range(set) { fmt.Println(key)}// each value will be printed only once, in no particular order// you can use the ,ok idiom to check for existing keysif _, ok := set[1]; ok { fmt.Println("element found")} else { fmt.Println("element not found")}


