小编典典

Go 是否具有类似于 Python 的“if x in”结构?

go

如果不遍历整个数组,如何x使用 Go检查数组中是否存在?语言有结构吗?

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


阅读 206

收藏
2021-10-31

共1个答案

小编典典

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

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

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

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