2015-05-26 29 views
4

Does Go是否有类似Python的in关键字?我想检查一个值是否在列表中。检查一个值是否在列表中

例如在Python:

x = 'red' 

if x in ['red', 'green', 'yellow', 'blue']: 
    print "found" 
else: 
    print "not found" 

在围棋,我想出了使用设定的成语,但我不认为这是理想的,因为我必须指定,我不是用int值。

x := "red" 

valid := map[string]int{"red": 0, "green": 0,"yellow": 0, "blue": 0} 

if _, ok := valid[x]; ok { 
    fmt.Println("found") 
} else { 
    fmt.Println("not found") 
} 

我知道有一个in关键字可能与泛型有关。有没有办法做到这一点使用去生成或什么?

+1

另请参阅[http://stackoverflow.com/questions/15323767/how-to-if-x-in-array-in-golang](http://stackoverflow.com/questions/15323767/how-to- if-x-in-array-in-golang) – IamNaN

+0

为什么它没有被作为重复关闭? –

回答

10

您可以使用map[string]bool作为一个集合。当测试和一个键不在地图中时,返回的bool的零值为false

因此请填写有效值作为关键字和true作为值的地图。如果测试的键值在地图中,则其结果将存储其存储的true值。如果测试的键值不在映射中,则返回值类型的零值,即false

利用这一点,测试变成这个简单:

valid := map[string]bool{"red": true, "green": true, "yellow": true, "blue": true} 

if valid[x] { 
    fmt.Println("found") 
} else { 
    fmt.Println("not found") 
} 

尝试它的Go Playground(与变种下面提到)。

这在博客文章中提到:Go maps in action: Exploiting zero values

注:

如果你有很多有效的值,因为存储在地图中的所有值都true,它可以更紧凑使用切片列出的有效值,并使用for range环路初始化地图,是这样的:

for _, v := range []string{"red", "green", "yellow", "blue"} { 
    valid[v] = true 
} 

注2:

如果你不想去的for range环路初始化,你仍然可以优化它一点点通过创建无类型(或bool -typed)一个字母const

const t = true 
valid := map[string]bool{"red": t, "green": t, "yellow": t, "blue": t} 
+0

对于大集合,使用map [string] struct {}而不是map [string] bool可能会节省空间,因为空结构占用零空间。存在测试需要使用两个值形式'_,exists:= valid [x]'。首先使用空结构体文字'{}'而不是bool'true'来创建地图。 –

相关问题