Go是否具有“if x in”构造类似于Python? [英] Does Go have "if x in" construct similar to Python?

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

问题描述

没有迭代整个数组怎么样,我可以检查Go中数组中的 x 吗?

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

与Python类似:如果数组中的x:...

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

推荐答案

在Go中没有内置运算符。您需要遍历数组。您可以编写自己的函数来执行此操作,如下所示:

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.")
}

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

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