How to check if a map contains a key in go?

I know I can iterate over a map m by,

for k, v := range m { ... }

and look for a key but is there a more efficient way of testing a key's existence in a map? Thanks. I couldn't find an answer in the language spec.


One line answer:

if val, ok := dict["foo"]; ok {
    //do something here
}

Explanation:

if statements in Go can include both a condition and an initialization statement. The example above uses both:

  • initializes two variables - val will receive either the value of "foo" from the map or a "zero value" (in this case the empty string) and ok will receive a bool that will be set to true if "foo" was actually present in the map

  • evaluates ok , which will be true if "foo" was in the map

  • If "foo" is indeed present in the map, the body of the if statement will be executed and val will be local to that scope.


    Edit: The following answer is prior to Go 1. Starting with Go 1, it is no longer accurate / valid.


    In addition to The Go Programming Language Specification, you should read Effective Go. In the section on maps, they say, amongst other things:

    "An attempt to fetch a map value with a key that is not present in the map will cause the program to crash, but there is a way to do so safely using a multiple assignment."

    var seconds int
    var ok bool
    seconds, ok = timeZone[tz]
    

    "To test for presence in the map without worrying about the actual value, you can use the blank identifier, a simple underscore (_). The blank identifier can be assigned or declared with any value of any type, with the value discarded harmlessly. For testing presence in a map, use the blank identifier in place of the usual variable for the value."

    _, present := timeZone[tz]
    

    Searched on the go-nuts email list and found a solution posted by Peter Froehlich on 11/15/2009.

    package main
    
    import "fmt"
    
    func main() {
            dict := map[string]int {"foo" : 1, "bar" : 2}
            value, ok := dict["baz"]
            if ok {
                    fmt.Println("value: ", value)
            } else {
                    fmt.Println("key not found")
            }
    }
    

    Or, more compactly,

    if value, ok := dict["baz"]; ok {
        fmt.Println("value: ", value)
    } else {
        fmt.Println("key not found")
    }
    

    Note, using this form of the if statement, the value and ok variables are only visible inside the if conditions.

    链接地址: http://www.djcxy.com/p/23992.html

    上一篇: 如果你总是喜欢xrange()超过范围()?

    下一篇: 如何检查地图中是否包含密钥?