如何在地图中的整数数组中包含唯一元素?

How to have unique elements in integer array within a map?

我有一个字符串和 int 数组的映射,如下所示,正在填充 -

  var customerCatalog = make(map[string][]int64)
  for ... {
        var data = "....."
        for _, catalogId := range data.Catalogs {
            var ok bool
            var keys []int64
            var tmp interface{}
            cusId := strconv.FormatInt(int64(catalogId), 10)
            if tmp, ok = customerCatalog[cusId]; !ok {
                keys = []int64{}
            } else {
                keys = tmp.([]int64)
            }
            keys = append(keys, data.ProductId)
            customerCatalog[cusId] = keys
        }
    }

这里data.Catalogs是int32数组。而 data.ProductId 是 int64。所以我需要遍历 data.Catalogs 数组并使用每个 data.ProductId 键的唯一数组值填充我的 customerCatalog 映射。

如您所见,我将 map 的值作为整数数组,其中可以包含重复值。我想确保地图中特定键的整数数组中应该有唯一的值。由于 go 不支持泛型,所以我们没有设置,所以我们应该如何处理这里的情况?

Since go doesn't support generics so that is why we don't have set

集合通常使用散列的键实现 table;忽略值。

在 Go 中,使用 map[int64]bool

// Check if an array contains only unique values.
func is_unique(array []int64) bool {
  var unique = map[int64]bool{}

  for _,v := range(array) {
    if unique[v] {
      return false
    }
    unique[v] = true
  }

  return true
}

// Return a deduplicated array
func uniq(array []int64) []int64 {
  var unique = map[int64]bool{}
  keys := make([]int64, 1)

  for _,v := range(array) {
    if _, ok := unique[v]; !ok {
      keys = append(keys, v)
      unique[v] = true
    }
  }

  return keys
}