简体   繁体   中英

Golang syntax in “if” statement with a map

I am reading a tutorial here: http://www.newthinktank.com/2015/02/go-programming-tutorial/

On the "Maps in Maps" section it has:

package main

import "fmt"

func main() {

    // We can store multiple items in a map as well

    superhero := map[string]map[string]string{
        "Superman": map[string]string{
            "realname":"Clark Kent",
            "city":"Metropolis",
        },

        "Batman": map[string]string{
            "realname":"Bruce Wayne",
            "city":"Gotham City",
        },
    }

    // We can output data where the key matches Superman

    if temp, hero := superhero["Superman"]; hero {
        fmt.Println(temp["realname"], temp["city"])
    }

}

I don't understand the "if" statement. Can someone walk me through the syntax on this line:

if temp, hero := superhero["Superman"]; hero {

Like if temp seems nonsensical to an outsider as temp isn't even defined anywhere. What would that even accomplish? Then hero := superhero["Superman"] looks like an assignment. But what is the semicolon doing? why is the final hero there?

Can someone help a newbie out?

Many thanks.

It's more normal to use ok for the boolean variable name. This is equivalent to:

temp, ok := superhero["Superman"]
if ok {
    fmt.Println(temp["realname"], temp["city"])
}

The ok is true if there was a key in the map. So there are two forms of map access built into the language, and two forms of this statement. Personally I think this slightly more verbose form with one more line of code is much clearer, but you can use either.So the other form would be:

if temp, ok := superhero["Superman"]; ok {
    fmt.Println(temp["realname"], temp["city"])
}

As above. For more see effective go here:

For obvious reasons this is called the “comma ok” idiom. In this example, if the key is present, the value will be set appropriately and ok will be true; if not, the value will be set to zero and ok will be false.

The two forms for accessing maps are:

// value and ok set if key is present, else ok is false
value, ok := map[key]

// value set if key is present
value := map[key]

A two-value assignment tests for the existence of a key:

i, ok := m["route"]

In this statement, the first value (i) is assigned the value stored under the key "route". If that key doesn't exist, i is the value type's zero value (0). The second value (ok) is a bool that is true if the key exists in the map, and false if not.

This check is basically used when we are not confirmed about the data inside the map. So we just check for a particular key and if it exists we assign the value to variable. It is a O(1) check.

In your example try to search for a key inside the map which does not exists as:

package main

import "fmt"

func main() {

    // We can store multiple items in a map as well

    superhero := map[string]map[string]string{
        "Superman": map[string]string{
            "realname": "Clark Kent",
            "city":     "Metropolis",
        },

        "Batman": map[string]string{
            "realname": "Bruce Wayne",
            "city":     "Gotham City",
        },
    }

    // We can output data where the key matches Superman

    if temp, hero := superhero["Superman"]; hero {
        fmt.Println(temp["realname"], temp["city"])
    }

    // try to search for a key which doesnot exist

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

}

Playground Example

if temp, hero := superhero["Superman"]; hero

in go is similar to writing:

temp, hero := superhero["Superman"]
if hero {
    ....
}

Here is "Superman" is mapped to a value, hero will be true

else false

In go every query to a map will return an optional second argument which will tell if a certain key is present or not

https://play.golang.org/p/Hl7MajLJV3T

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM