Dictionary golang是否有支持set数据结构的计划?

Dictionary golang是否有支持set数据结构的计划?,dictionary,go,set,Dictionary,Go,Set,此功能可通过“映射”实现 countrySet := map[string]bool{ "US": true, "JP": true, "KR": true, } 但为了便于读者阅读,“set”是一种必要的数据结构 countrySet := set[string]{"US", "JP", "KR"} 或仅使用键初始化“映射”。例如: countrySet := map[string]bool{"US", "JP", "KR"} golang有支持这种语法的计划吗?我不知道这

此功能可通过“映射”实现

countrySet := map[string]bool{
  "US": true,
  "JP": true, 
  "KR": true,
}
但为了便于读者阅读,“set”是一种必要的数据结构

countrySet := set[string]{"US", "JP", "KR"}
或仅使用键初始化“映射”。例如:

countrySet := map[string]bool{"US", "JP", "KR"}

golang有支持这种语法的计划吗?

我不知道这样的计划

您可以采取哪些措施来简化初始化:

使用一个字母
bool
常量:

const t = true
countrySet := map[string]bool{"US": t, "JP": t, "KR": t}
countrySet := map[string]bool{}
for _, v := range []string{"US", "JP", "KR"} {
    countrySet[v] = true
}
func createSet(es ...string) map[string]bool {
    m := map[string]bool{}
    for _, v := range es {
        m[v] = true
    }
    return m
}
使用循环添加键,因此只需列出键:

const t = true
countrySet := map[string]bool{"US": t, "JP": t, "KR": t}
countrySet := map[string]bool{}
for _, v := range []string{"US", "JP", "KR"} {
    countrySet[v] = true
}
func createSet(es ...string) map[string]bool {
    m := map[string]bool{}
    for _, v := range es {
        m[v] = true
    }
    return m
}
只有当你有更多的元素时,这才是有利可图的

但您始终可以创建助手函数:

const t = true
countrySet := map[string]bool{"US": t, "JP": t, "KR": t}
countrySet := map[string]bool{}
for _, v := range []string{"US", "JP", "KR"} {
    countrySet[v] = true
}
func createSet(es ...string) map[string]bool {
    m := map[string]bool{}
    for _, v := range es {
        m[v] = true
    }
    return m
}
然后使用它:

countrySet := createSet("US", "JP", "KR")

计划不是支持Go标准库中的所有内容。该计划旨在鼓励独立开发的开源软件包。比如说,很多,

导入“k8s.io/apimachinery/pkg/util/sets”

包集具有自动生成的集类型


我认为
map[string]bool
是一个不错的选择。另一个选择是
映射[字符串]结构{}

package main
import "fmt"

func main() {
   s := map[string]struct{}{
      "JP": {}, "KR": {}, "US": {},
   }
   s["UA"] = struct{}{}
   if _, ok := s["UA"]; ok {
      println("ok")
   }
   fmt.Println(s)
}
它比bool稍好一些,因为值占用0字节而不是1字节 字节,但使用起来有点尴尬。另一个选择是
fstest.MapFS

package main

import (
   "fmt"
   "testing/fstest"
)

func main() {
   s := fstest.MapFS{"JP": nil, "KR": nil, "US": nil}
   s["UA"] = nil
   if _, ok := s["UA"]; ok {
      println("ok")
   }
   a, e := s.Glob("U*")
   if e != nil {
      panic(e)
   }
   fmt.Println(a) // [UA US]
}
这很好,因为您可以对集合项进行模式匹配


不,Go永远不会支持此功能,因为它没有意义。如果不提供它,就无法知道值应该是什么。但是在将来,如果你想知道围棋的计划,或者提出你自己的想法,只需访问。还要考虑:如果你知道这个值总是正确的,那么使用
bool
是完全没有必要的。您可以通过使用
map[string]struct{}
将映射用作任意键的唯一列表。读取和设置有点麻烦,但它更清楚地表达了意图,因为
struct{}
根本不能包含任何值。这是一个
map[string]nil
。谢谢@Flimzy,在我的机器学习场景中,“set”是一个非常频繁的数据结构,所以我尝试找到一种初始化set的简单方法。顺便说一句,在这种情况下,人们总是将python与之相比较。拥有
set
原语可能有意义,也可能没有意义——尽管Go不太可能采用。拥有一个
集合
库可能是有意义的(并且确实存在,正如答案中所提供的)。在任何情况下,您建议的
map
初始化语法都没有意义。感谢您提供了@icza的良好解决方案。但我认为内置数据结构是更有效的方法。VS Python(T_T)@cnby:如何提高效率?谢谢你的回答@peterSO。我用的是这样的包装纸。这是另一个。