Golang是否有“如果x进入”构造类似于Python? [英] Does Golang have "if x in" construct similar to Python?

查看:111
本文介绍了Golang是否有“如果x进入”构造类似于Python?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$ c>如果数组中包含x:...

解决方案

在运营商中使用Go。你需要遍历数组。你可以编写自己的函数来完成它,如下所示:

  func stringInSlice(string,list [] string)bool { 
for _,b:=范围列表{
如果b == a {
返回true
}
}
返回false
}

如果您希望能够检查成员资格而无需遍历整个列表,则需要使用一个映射,而不是一个数组或切片,如下所示:

  visitedURL:= map [string] bool {
http://www.google.com:true,
https://paypal.com:true,
}
如果visitedURL [thisSite] {
fmt。 Println(已经在这里)
}


Without iterating over the entire array how can I check if 'x' in array in Go?

Like Python: if "x" in array: ...

解决方案

There is no built-in operator to do it in Go. You need to iterate over the array. You can write your own function to do it, like this:

func stringInSlice(a string, list []string) bool {
    for _, b := range list {
        if b == a {
            return true
        }
    }
    return false
}

If you want to be able to check for membership without iterating over the whole list, you need to use a map instead of an array or slice, like this:

visitedURL := map[string]bool {
    "http://www.google.com": true,
    "https://paypal.com": true,
}
if visitedURL[thisSite] {
    fmt.Println("Already been here.")
}

这篇关于Golang是否有“如果x进入”构造类似于Python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆